Search code examples
reactjsnode.jsfetch-apidisplay

can't display my message with fetch api reactJS/nodeJS


I want to use a fetch API call. To try if it works I try to show a message.

In my nodeJs server i've:

app.get('/api', (req, res) => {
res.send({
    message: 'Hi'
})

})

In my frontend folder, in my app.js:

 import React, {useState} from 'react';

  const App = () => {

  const [message, setMsg] = useState('');
  
  const handleClick = async () => {
    console.log('click');

    fetch('/api')
      .then((response) => {
        return response.json();
      })
      .catch((error) => {
        console.error(`${error}`)
      })
      .then(json => console.log(json))
      .catch((error) => {
        console.error(`Couldn't convert the json: ${error}`)
      });
    setMsg(message);
  };
  
  return (
    <div className="App">
        <button onClick={handleClick}>
          Button
        </button>
        <p>{message}</p>
    </div>
  );
}

export default App;

Everythings is ok, when i load my app in my browser, i've no error in my inspector, when i click on my button: my console shows:

click

my json shows:

{message: 'Hi'} >message: "Hi" >[[Prototype]]: Object

But my message doesn't works for <p>{message}<p>

when i put 'test' in setMsg(console.log('test')) it works. when i put it in <p>test</p> it works

I really don't understand my <p>{message}</p> doesn't display..

Thanks for your help


Solution

  • This should work for you:

    const handleClick = async () => {
        console.log('click');
        fetch('/api')
          .then((response) => {
            return response.json();
          })
          .catch((error) => {
            console.error(`${error}`)
          })
          .then(json => {
            setMsg(json.message)
          })
          .catch((error) => {
            console.error(`Couldn't convert the json: ${error}`)
          });
    };