Home > database >  How to use a value changed by useEffect?
How to use a value changed by useEffect?

Time:06-05

So I have my code like this:

var problems = ['a','b','c'];
  var allProblemStatus;
  var selectProblemStatus = "";

  useEffect(() => {
    let getProblemStatus = async() => {
      let response = await fetch('http://127.0.0.1:8000/api/problem-status/');
      allProblemStatus = await response.json();
      selectProblemStatus = allProblemStatus['problem_status'];
    }
    getProblemStatus();
  }, []);

return (
    <div>
    {problems.map((problem, index) => (
        <Grid item xs={200} md={100} lg={5}>
          <Problem key={index} problem={problem} a={selectProblemStatus} />
        </Grid>
      
      ))}
    </div>
  );

selectProblemStatus is being changed in useEffect but how do I actually use it to pass it to the Problem component as a prop, also is there a way to console.log the changed selectProblemStatus

CodePudding user response:

it is clear that you are unfamiliar with useState hook in react. your approach should be look like this:

import { useState } from 'react'

const YourComponent = (props) => {
  const [problems, setProblems] = useState([])
  
  const getProblemStatus = async () => { ... }

  useEffect(() => {
    getProblemStatus()
  }, [])

  return (
    <div>
    {problems.map((problem, index) => (
        <Grid item xs={200} md={100} lg={5}>
          <Problem key={index} problem={problem} a={selectProblemStatus} />
        </Grid>
      
      ))}
    </div>
  )
}

CodePudding user response:

You can use useState() hook for your variables, and then in useEffect update them. Here is link how to use useState https://uk.reactjs.org/docs/hooks-state.html

  • Related