skip to Main Content

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


  1. Just change this

    const {message, setMessage} = useState("")
    

    to this

    const [message, setMessage] = useState("")
    
    Login or Signup to reply.
  2. 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.

    let foo = ['a', 'b']
    const {x1, y1} = foo;
    const [x2, y2] = foo;
    
    console.log(x1, y1);
    console.log(x2, y2);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search