0

I'm trying to dynamically initialize context based on a variable from within the context, the dynamic variable is an empty array of length N, where N=size which is part of the context.

I would like the default size to be 5 unless overridden in the context.

const createArray = (size) =>{
    let myArray = []

    for (let i=0; i<size, i++){
        myArray.push(false);
    }
    return myArray
};


export const initialState = {
    name : "",
    size: 5,
    slotArray : createArray(size),
}

I'm getting an error 'size' is not defined

However, if I hardcode the following it will work just fine. What am I doing wrong?

slotArray : createArray(5)

Thanks in advance

ortunoa
  • 345
  • 4
  • 11

1 Answers1

2

The variable size is not defined when creating the initialState object.

It is available in the scope of the 'createArray' arrow function, because 'size' is passed as a parameter.

Read more about JS scope and closures here

Answer to the original question, you'd do something like

const createArray = (size) =>{
  let myArray = []
  for (let i=0; i<size, i++){
    myArray.push(false);
  }
  return myArray
};


const MyContext = React.createContext(null);

function parentComponent() {
  const arrLength = null; // Change this dynamically

  return (
     <MyContext.Provider value={arrLength}>
       <h1>This is the Parent Component</h1>
       <ChildComponent />
     </MyContext.Provider>
   );

const getInitialState = (size) => {
  name : "",
  size: 5,
  slotArray : createArray(size),
}

function ChildComponent(props) {
const myDynamicArrLength = React.useContext(MyContext);
const myArr = getInitialState(myDynamicArrLength || 5);

return (<div>
    {myArr.slotArray.map((a)=> a ? <span>true</span>:<span>false</span>)}
  </div>);
}
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29
  • Can I tie the size of these arrays to a context variable? For example if 'size' were to change to 4, how can I dynamically have 'slotArray' change to [false,false,false,false] ? Isn't size available inside of the initialState object? – ortunoa Jun 28 '21 at 20:05
  • Show us the whole component - the way to do it depends on component workflow. What you have here is two javascript functions, and no react. – Jkarttunen Jul 01 '21 at 07:17
  • Edited the answer for example – Jkarttunen Jul 01 '21 at 07:33