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);
});
};
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.