Home > Software design >  How can I pass data to an object using React Hooks and Redux
How can I pass data to an object using React Hooks and Redux

Time:11-15

I am trying to pass data that I get from a data base to an object, using react and redux. I cant figure out what Im doing wrong

This is my code

const [orders, setOrders] = useState([]);

useEffect(() => {
    props.fetchOrder(setOrders);
}, []);

console.log(orders);

const columnsFromBackend = {
    newOrder: {
        name: "Requested",
        items: orders
    },
    x: {
        name: "x",
        items: []
    }
};
const [columns, setColumns] = useState(columnsFromBackend);

console.log(columns);

the result is the page renders twice, in the console it shows, fir

orders = []

columns = {newOrder: {…}, x: {…}}

in the second time

orders = (39) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

columns = {newOrder: items: []}

the items property inside newOrder object should have been equal to orders, but it stayed empty

How do I pass into the items property the data of orders correclty?

just for clearance, this is the fetch function from the redux actions

export const fetchOrder = setOrders => dispatch => {
    fetch("/api/orders")
        .then(res => res.json())
        .then(data => {
            setOrders(data);
            dispatch({ type: FETCH_ORDER, payload: data });
        });
};

Thank you and have a nice day

CodePudding user response:

You need to update columns whenever the orders get updated. For that, you need to have another useEffect hook in your code like below.

useEffect(() => {
    setColumns(prevState => {
        return {
            ...prevState,
            x: {
                ...prevState.x,
                items: orders
            }
        };
    });
}, [orders]);
  • Related