0
votes

I am new to React, and even newer to Redux. All I want to do is output the contents of the array to the webpage. I want to maintain the Redux structure (unidirectional data flow, reducers). When I click the Generate a New Array button, an array gets generated by the reducer and saved as state. In my attempts to output the array using map, I see errors telling me that myarray.map is not a function. I am a bit confused considering I am pulling the array from state, and it should be populated.

Initial State

const initialState = {
  array: [],
  algo: null,
  size: 30,
}

Reducers

const arrayReducer = (state,action) => {
  if (action.type === GENERATE_NEW_ARRAY){
    let arr = [];
    let size = state.size;
    let limit = size*3;

    for(let i=0;i<size;++i){
      let num = Math.floor((Math.Random() * limit) + 1);
      arr.push(num);
    }

    return { array: arr };
  }
  return state || { array: [] };
};

const rootReducer = combineReducers({
  array: arrayReducer,
  algo: algoReducer,
  size: sizeReducer,
});

Selector

const getSize = state => state.size;

React Components

function GenerateNewArray({ value, generateNewArray }){
  return(
    <div>
      <button onClick={() => generateNewArray(value)}>
        Generate a New Array
      </button>
    </div>
  )
}
const GenerateNewArrayConnected = connect(
  state => ({
    size: getSize(state)
  }),
  dispatch => ({
    generateNewArray: size => dispatch(generateNewArray(size))
  })
)(GenerateNewArray);

I would like the array to appear below the Generate a New Array button, but I would like it as a separate entity (if possible) because they ultimately will be two separate components. What is the best way to approach displaying the array?

1
can you include the code that has myarray.map please?Zeke Hernandez

1 Answers

0
votes

Assuming that the initialState is defined for your rootReducer, you just need to return the array from arrayReducer instead of {array: arr}

const arrayReducer = (state,action) => {
  if (action.type === GENERATE_NEW_ARRAY){
    let arr = [];
    let size = state.size;
    let limit = size*3;

    for(let i=0;i<size;++i){
      let num = Math.floor((Math.Random() * limit) + 1);
      arr.push(num);
    }

    return arr;
  }
  return state;
};