Home > front end >  How to change useState from inside of Child Component
How to change useState from inside of Child Component

Time:10-24

I am trying to import CSVs inside a Importer Component and pass on the Data to the Parent and change useState there...

So here i am trying to call said Component and pass on the useState function.

  const [database, setDatabase] = useState([]);

  useEffect(() => {
    <Importer setdata={(data) => setDatabase([...data])} />;
  }, []);

and Child Component is importing the CSV and passing on the data to be displayed after changing the State with useState:

const importAllCsv = (props) => {
  text("template.csv").then((data) => {
    //console.log(data);
    const psv = dsvFormat(";");
    //console.log(psv.parse(data));
    DATABASE = psv.parse(data);
    console.log(DATABASE);
    props.setdata(DATABASE);
  });
};

export default function Importer(props) {
  return importAllCsv(props);
}

CodePudding user response:

props.setdata((prevState) => [...prevState, ...DATABASE]) and try to include it on return ( ); not on use effect hope this helps

CodePudding user response:

Components must start with a capital letter, also avoid returning components in useEffect when you can return them in the return part of the parent component.

As Aliyan said, try props.setdata((prevState) => [...prevState, ...DATABASE])

CodePudding user response:

As per my understanding, you want to update the parent's state through a child component, for this you can simply pass the currentState (if required) and the setState function to the child as a prop using the following method :

export default function App() { //Parent Component
  const [state, setState] = useState(1);
  return (
    <div className="App">
      <div>{state}</div>
      <ChildComponent setParentState={setState} currentState={state}/>
    </div>
  );
}

function ChildComponent({ setParentState, currentState }) { 
  function UpdateState() {
    setParentState(currentState 1);
  }
  return <button onClick={() => UpdateState()}>Update State</button>;
}
  • Related