In a React project, I've two screens in which one screen array is created and passed as props to other screen. The second screen doesn't display the array data. Please refer to the code below
Below is the JSON data from first screen
const newCompData = [
{
id: 1,
comp: "McDonalds",
feedback: "Best Food Chain",
name: "Mike John",
store: "Burger Store"
},
{
id: 2,
comp: "KFC",
feedback: "Best Chicken Products",
store: "Chicken Food",
name: "Steve Williams"
},
{
id: 3,
comp: "Dominos",
feedback: "Best Pizza Store",
store: "Pizza Store",
name: "Mark Rays",
},
{
id: 4,
comp: "Star Bucks",
feedback: "Best Coffee Store",
store: "Coffee Store",
name: "Patrick Right",
},
{
id: 5,
comp: "Burger King",
feedback: "Best Burgers",
store: "Burger Store",
name: "Williams Wills"
},
{
id: 6,
comp: "Lays",
feedback: "Best Chips Factory",
store: "Chips Store",
name: "Sam Andrews",
}
];
This is how I map the above array of object data
const [dataAll, setDataAll] = useState([]);
useEffect(() => {
const newData = newCompData?.map((data) => {
return [{ id: data.id }, data.comp, data.store, data.name, data.feedback];
});
setDataAll(newData);
}, []);
return (
<div className="App">
<Table newData={dataAll} />
</div>
);
Now the second screen Table.js
const Table = ({ newData }) => {
// Checking for newData value and is getting in console
console.log("PROPS", newData);
const store_grid_data = {
data: newData,
page_info: {
total_pages: 5,
current_page: 1
}
};
let GridConfig = {};
let grid_data = {};
GridConfig = TableConfig;
grid_data = store_grid_data;
const [gridConfigData, setGridConfigData] = useState(GridConfig);
const [gridData, setGridData] = useState(grid_data);
return (
<>
<Grid GridConfig={gridConfigData} GridData={gridData} />
</>
);
};
Array data isn't getting displayed in the above mentioned second screen. The data which I've created is similar as JSON data from API. What could be the best solution to tackle this issue. Any suggestions highly appreciated
Following is the codesandbox link: https://codesandbox.io/s/bold-boyd-2e16j6
CodePudding user response:
Please change Table.js file render function, here we don't need to set gridValue using useState(), you can pass that value directly in props
import TableConfig from "./TableConfig";
import { useState } from "react";
import Grid from "./Grid";
const Table = ({ newData }) => {
console.log("PROPS", newData);
const store_grid_data = {
data: newData,
page_info: {
total_pages: 5,
current_page: 1
}
};
return (
<>
<Grid GridConfig={TableConfig} GridData={store_grid_data} />
</>
);
};
export default Table;