I'm trying to render some cards through the mapping of an array.
My parent component seems to be consuming the information but the cards are still not rendering. In the example below I went back to basics and I'm not including the cards, I'm just trying to render an h1
in the parent component, and that also doesn't work:
This is my parent component:
export const Home = () => {
const { store, actions } = useContext(Context);
const data_types = Object.keys(store.results);
useEffect(() => {
for (let data_type of data_types) {
actions.getData(data_type)
}
}, []);
return (
<div className="text-center mt-5">
{data_types.map((data_type) => {
store.results[data_type].map((item, index) => {
<div className="container mb-4">
{console.log(index, item)}
<h1>{item}</h1>
</div>
})
This is how I fetch and store the data:
const getState = ({ getStore, getActions, setStore }) => {
return {
store: {
results: {
people: [],
planets: [],
starships: [],
vehicles: [],
}
},
actions: {
getData: async (data_type) => {
const local_results = JSON.parse(localStorage.getItem("results"));
if (local_results !== null && local_results[data_type].length > 0) {
console.log(`The data type ${data_type} is already in local storage`)
let result = {}
result[data_type] = [...local_results[data_type]]
setStore({
results: {
...getStore().results,
...result
}
})
return
}
const baseURL = `https://swapi.dev/api/${data_type}/`;
try {
const response_1 = await fetch(`${baseURL}`);
const data_1 = await response_1.json();
const response_2 = await fetch(`${data_1.next}`);
const data_2 = await response_2.json();
let result = {}
result[data_type] = [...data_1.results, ...data_2.results]
setStore({
results: {
...getStore().results,
...result
}
})
localStorage.setItem("results", JSON.stringify(getStore().results));
} catch (error) {
console.log(`Error loading message from https://swapi.dev/api/${data_type}/`, error);
}
}
This is the console print out:
I've also tried using a React State like this:
export const Home = () => {
const { store, actions } = useContext(Context);
const [arr, setArr] = useState([])
const data_types = Object.keys(store.results);
useEffect(() => {
for (let data_type of data_types) {
actions.getData(data_type)
}
setArr(store.results);
}, []);
return (
<div className="text-center mt-5">
{data_types.map((data_type) => {
arr !== "undefined" && data_type in arr ? arr[data_type].map((item, index) => {
<div className="container mb-4">
{console.log(index, item)}
<h1>{item}</h1>
</div>
}) : null
})
}
</div>
)
}