0

I am sending data and getting data with Axios. Data is coming, i can see it with console.log(res.data) but I can't apply res.data to setMessages

  const [formData, setFormData] = useState({ input: null });

  const [messages, setMessages] = useState([]);

  const { input } = formData;

  const onChange = e => setFormData({ input: e.target.value });

  const onSubmit = event => {
    event.preventDefault();
    const data = new FormData(event.target);
    setMessages(prevMsgs => [...prevMsgs, formData]);

    console.log({ input });

    axios
      .post(`http://localhost:4000/prediction`, (data: data), {
        crossdomain: true
      })
      .then(res => {
        console.log(res.data);
        setMessages(prevMsgs => [...prevMsgs, res.data]);
      })
      .catch(error => {
        console.log(error.message);
      });
  };
zicxor
  • 99
  • 1
  • 2
  • 15
  • What's the data type of `res.data`? Can you add the output of `console.log(res.data)`? – Gustav Feb 26 '20 at 18:30
  • Hi @Gustav, to me, input is **normal text data**. In Network, it says `Content-Type: text/javascript` but in Postman, it says `Content-Type: application/json` Output of `console.log(res.data)`: "test" – zicxor Feb 26 '20 at 18:58
  • This works: https://codesandbox.io/s/agitated-waterfall-o4tw7?expanddevtools=1 and is very similar to your example aside from the fact it's a get not a post – Andy Mardell Feb 26 '20 at 19:43
  • @AndyMardell I updated my code, but **useEffect** is not working with onSubmit. It says: _React Hook "useEffect" is called in function "onSubmit" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks_ – zicxor Feb 28 '20 at 17:28

1 Answers1

1

In your code you are performing a async operation directly. To perform async operation in functional component 'useEffect' hook should be used depending upon the mount/update requirements.

Just like in class component a async operation are performed from componentDidMount lifecycle event method, useEffect hook is successor of componentDidMount, componentDidUpdate and componentWillUnmount in functional components.

componentDidMount equivalent on a React function/Hooks component?

  • But **useEffect** is not working with onSubmit. It says: _React Hook "useEffect" is called in function "onSubmit" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks_ – zicxor Feb 28 '20 at 17:29
  • Its been so late, but context about calling hooks was making api call before on Submit click that is writing and using outside the onSubmit callback.Other way around is to use async await, that is write await the point of api call in onSubmit and update the state on Success. – girijashankar_j Aug 15 '23 at 01:29