skip to Main Content

So i have a code here of me getting my users data so its like this in postman
enter image description here

now when i do it in frontend its not fetching the data of it this is the hook state of my code

  const [records, setRecords] = useState([]);

  useEffect(() => {
    const fetchUser = async () => {
      const records = await axios.get('/api/users')
      setRecords(records)
    };
    fetchUser();
  }, [])

and this is the example of me getting the first_name data


 <div>
          <ul>
            {records.map((record, index) => {
              return <li key={index}>{record.email_address}</li>
            })}
          </ul>
         </div>

2

Answers


  1. axios.get returns an HTTP response, not just the contents. Use the data property and this should work.

    const [records, setRecords] = useState([]);
    
      useEffect(() => {
        const fetchUser = async () => {
          const res = await axios.get('/api/users')
          setRecords(res.data)
        };
        fetchUser();
      }, [])
    
    Login or Signup to reply.
  2. It’s returns a response as well. take a look at the following code-

       
    
    
      useEffect(() => {
        const fetchUser = async () => {
          const records = await axios.get('/api/users').then((response) => {
    
            setRecords(response.data)
          })
        };
        fetchUser();
      }, []);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search