How to set or update state of Array in grand child component

Viewed 52

I'm trying to set state of array from grand child component which is located in parent component.

I tried to use setNumberOfVar([...varsLines]); this method but it's not updating the state immediately.it updates but one step back.

My Code


  const removeVar = (e, val) => {
    e.preventDefault();
    var varsLines = numberOfVar;
    varsLines = numberOfVar.filter((item) => {
      return item.postion != val;
    });
    varsLines = varsLines.map((item) => {
      return {
        ...item,
        postion: item.postion > val ? item.postion - 1 : item.postion,
      };
    });
    console.log(varsLines);
    setNumberOfVar([...varsLines]); // <== this line is not updating the state immediately;
    console.log(numberOfVar);
  };

2 Answers

setNumberOfVar() is an async operation and will not update state immediately.

If you want to get something like a callback when the state is updated, you can use the useEffect hook that runs on state update.

import {useEffect } from 'react';

  useEffect(() => {
    console.log(numberOfVar);
  },[numberOfVar]); 

try to do something like this

setNumberOfVar(prevState=>prevState.filter().map())

use your own conditions in filter and map and see if it's working or not.

Related