Home > Mobile >  I am fetching my backend using axios in React. It is not displaying the data even though the state h
I am fetching my backend using axios in React. It is not displaying the data even though the state h

Time:10-23

I am fetching my backend using axios. The data is fetched correctly. I am using MongoDb. I can see that the state has changed to an array of objects correctly in the react dev tools. However, it is not being displayed in my webpage.

This is a simple code, i am testing the api, I could not figure out what is wrong because it is pretty much straightforward and i have no clue why it is not working.

this is my code

import axios from "axios";
import React, { useEffect, useState } from "react";

function ApiTest() {
  const [users, setUsers] = useState([]);
  const fetchUsers = () => {
    axios
      .get("/api/users")
      .then((response) => {
        setUsers(response.data);
        console.log(response.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div>
      <button onClick={fetchUsers}>Fetch Users</button>
      <ul>
        {users.map((user) => {
          <li key={user._id}>{user.emai}</li>;
        })}
      </ul>
    </div>
  );
}

export default ApiTest;

CodePudding user response:

{users.map((user) => {
  return <li key={user._id}>{user.emai}</li>;
})}

you are not returning your list item

CodePudding user response:

you are not returning your list

import axios from "axios";
import React, { useEffect, useState } from "react";

function ApiTest() {
  const [users, setUsers] = useState([]);
  const fetchUsers = () => {
    axios
      .get("/api/users")
      .then((response) => {
        setUsers(response.data);
        console.log(response.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div>
      <button onClick={fetchUsers}>Fetch Users</button>
      <ul>
        {users.map((user) => {
         return (
            <li key={user._id}>{user.emai}</li>
         )
        })}
      </ul>
    </div>
  );
}

export default ApiTest;
  • Related