I try to fetch data from the server and then send it to the frontend.
function App() {
const {message, setMessage} = useState("")
useEffect(() => {
fetch(`http://localhost:8080/message`)
.then((res) => res.json())
// .then((data => console.log(data.message))) <---- This work just fine
.then((data) => setMessage(data.message))
})
return (
<div>
<h1>hi there</h1>
<h1>{message}</h1>
</div>
)
}
export default App;
I got this error on the console :
TypeError: setMessage is not a function
Console logging the data and rendering the ‘hi there’ heading was successful.
I didn’t know what went wrong, could anyone help me?
Thank you.
I tried to pass the setMessage an anonymous function, but that didn’t work too.
.then((data) => setMessage(() => data.message))
2
Answers
Just change this
to this
It’s just a problem with your destructuring assignment. Given the fact that you need to destructure an array, you need to enclose your variable names into
[
and]
instead of{
and}
, see the snippet below which illustrates the problem you faced.