0

I am getting undefined when I run the code below. However, If I console.log the results within the hook, I get all the data

hook (works fine, fetches the data)

import { useState, useEffect } from 'react';
import axios from 'axios';

export const GetOrders = () => {
    const [data, setData] = useState();

    useEffect(() => {
        axios.get('/allorders').then(res => {
            setData(res.data);
        });
    }, []);

    console.log(data);

    return { data };
};

component (returns undefined when I log the data)

import React from 'react';
import { GetOrders } from '../hooks/orders';

export const AllOrders = () => {
    const { data } = GetOrders();

    console.log(data);
    return (
        <ul>
            {data.forEach(order => (
                <li>{order.status}</li>
            ))}
        </ul>
    );
};
0

1 Answer 1

3

Your code looks good. Just initialize data with [] value so it will not break when you will loop over values since undefined.map() will fail

const [data, setData] = useState([]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.