Home > Back-end >  How do I update dynamic array inside useEffect in Typescript?
How do I update dynamic array inside useEffect in Typescript?

Time:12-22

I have an array declared as

 var subjects : string[] = [];

Then set the array with the values as

subjects.push("C")
subjects.push("C  ")

Then I want to update this array from useEffect. I tried below code

  useEffect(()=>{
    subjects.push("Java")
  },[])

when displaying subjects array, it is not updating with "Java". Can anyone help me to solve this?

CodePudding user response:

You are not triggering any re-rendering of your component. Re-renders run when props or states changes. You are trying to update an immutable piece of data in React world instead and the algorithm doesn't know that it changed, the UI doesn't reflect the updated subjects array as consequence.

So you could declare your subjects array in this way using the useState hook:

const [subjects, setSubjects] = useState<string[]>(["C  ", "C"])

Then you can update it in this way:

setSubjects((prev) => [...prev, 'Java']);

CodePudding user response:

Use hook useState for creating your array.

const [value, setValue] = useState<string[]>([])

And if you want change array, you should set new value as setValue([...value, "Java"]);

CodePudding user response:

Declare a state hook and store subjects values in it.

const [subjects, setSubjects] = useState<string[]>(["C", "C  "]);

Then in useEffect change the subjects value:

useEffect(()=>{
   const currentSubjects = [...subjects];
   currentSubjects.push("Java");
   setSubjects(currentSubjects);
},[])

CodePudding user response:

because you aren't using state variable(useState) and your subjects array has Java inside but that can't be visible until your component gets re-rendered so in my opinion you should use const [subjects, setSubjects] : string[] = useState<string[]>([]) and in useEffect:-

useEffect(()=>{
setSubjects([...subjects, 'Java']);},[])
  • Related