Home > Software engineering >  ReactJS can't fetch and display data from localhost API
ReactJS can't fetch and display data from localhost API

Time:04-21

Below is what I wrote for fetching the data from a localhost api that I wrote with Golang http://localhost:8081/post,

const HomePost1 = () => {
    const [author, setName] = useState('');

    const [title, setTitle] = useState('');


    useEffect(() => {
        (
            async () => {
                const response = await fetch('http://localhost:8081/post', {
                    headers: {'Content-Type': 'application/json'},
                    credentials: 'include',
                });

                const content = await response.json();

                setName(content.author)
                setTitle(content.title)
            }
        )();
    });

    return (
        <div>
            {"welcome "   author}
            {"content:"   title}
        </div>
    )
}

and I got this displayed on the web page, there is no error message:

welcome undefined content:undefined

The api from the localhost looks like this:

{
messges: [
{
   id: 2,
   title: "This is second sample post",
   author: "DEF"
},
{
   id: 3,
   title: "This is third sample post",
   author: "DEF"
}
]
}

I was using the exact same methods when I was fetching data from another api that I wrote and displayed the result successfully. What could be the problem to this? Is this caused by frontend or backend?

CodePudding user response:

Your api sent array so you should use map() instead of directly call content.title here is the working example.

const HomePost1 = () => {
const [res, setRes] = useState([]);

useEffect(() => {
    (
        async () => {
            const response = await fetch('http://localhost:8081/post', {
                headers: {'Content-Type': 'application/json'},
                credentials: 'include',
            });

            const content = await response.json();

            setRes(content.messges)
        }
    )();
});

return (

    <div>
       { res.map((rec, i ) => {
          return (<div key={i}>{"welcome "   rec.author}
          {"content:"   rec.title}</div>)
        }) }
    </div>
)
}

CodePudding user response:

By the api result, the response contains an array.

You may try to print out the variable "content" in console, to see the object structure.

I suggest you can try something like this:

content[0].title
// OR
content.messges[0].title
  • Related