Search code examples
javascriptreactjsreact-hooksuse-effect

How to use a value changed by useEffect?


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


Solution

  • 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 key={index} item xs={200} md={100} lg={5}>
              <Problem problem={problem} a={selectProblemStatus} />
            </Grid>
          ))}
        </div>
      )
    }