-1

I'm using React Hooks. I set the state property questions after an axios fetch call. Now when I click a button, in its function questions state is still empty

const [questions, setQuestions] = useState([]);
const [customComponent, setCustomComponent] = useState(<div />);

useEffect(() => {
  axios.get("urlhere").then(res => {
    console.log(12, res.data);
    setQuestions(res.data);

    res.data.map(q => {
      if (q.qualifyingQuestionId == 1) {
        setCustomComponent(renderSteps(q, q.qualifyingQuestionId));
      }
    });
  });
}, []);

const handleNext = i => {
  console.log(32, questions); //questions is still an empty array here
};

const renderSteps = (step, i) => {
  switch (step.controlTypeName) {
    case "textbox":
      return (
        <div key={i}>
          <input type="text" placeholder={step.content} />
          <button onClick={() => handleNext(i)}>Next</button>
        </div>
      );
  }
};

return <>{customComponent}</>;

Do I need to use reducers here and put the custom component in another "file"?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
idiglove
  • 325
  • 3
  • 10

2 Answers2

1

setQuestions does not update state immediately, you should use the prevState instead to access the new value.

Here's a sandbox to match your codes with some explanation on why it was empty > https://codesandbox.io/s/axios-useeffect-kdgnw

You can also read about it here: Why calling react setState method doesn't mutate the state immediately?

emzki
  • 88
  • 7
  • did this line "console.log(12, res.data)" log data from request? what's the actual log? – emzki Oct 31 '19 at 08:17
  • Here's a simulation of what you want to achieve, it is working properly and you can play with it https://codesandbox.io/s/axios-useeffect-kdgnw – emzki Oct 31 '19 at 08:31
  • Hi thanks for the effort. But I do can get the values of questions in return. My problem is getting `questions` once I click a button. the button has for ex., onClick = () => {console.log(questions)} that would only show an empty array – idiglove Nov 01 '19 at 01:01
  • 1
    Hi, I updated the sandbox to match your codes with some explanation on why it was empty > https://codesandbox.io/s/axios-useeffect-kdgnw You can also read about it here: https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately – emzki Nov 04 '19 at 09:50
  • I see! Thanks for your help! It's a weird workaround though, I didn't have to get prevState when not using Hooks – idiglove Nov 05 '19 at 10:07
  • @idglove Great to here that! By the way, I updated the answer to the correct one, you can mark it as the answer if it's correct to help future devs – emzki Nov 05 '19 at 10:21
0

Finally I have my own solution

I passed down the data from the fetch function to another component as props

useEffect(() => {
        axios.get('url')
        .then((data) => {
            setCustomComponent(<Questions questions={data} />)
        })
    }, [])
idiglove
  • 325
  • 3
  • 10