Okay so, basically when I'm testing the project locally, it shows but when I build and deploy to Firebase it doesn't show.
The data is pulled from a JSON file and I'm mapping it to show the list of categories.
The JSON file:
[
{
"title": "Title1",
"stack": ["React", "Firebase", "Styled Components"]
},
{
"title": "Title2",
"stack": ["Angular", "CSS", "HTML"]
},
{
"title": "Title3",
"stack": ["JavaScript", "VSCode"]
},
{
"title": "Title4",
"stack": ["Wordpress", "CSS", "PHP"]
}
]
The component:
import { useState, useEffect } from 'react';
import Projects from '../projects/projects.json';
import { v4 as uuidv4 } from 'uuid';
const CategoryList = () => {
const [projects, setProjects] = useState(Projects);
const [categories, setCategories] = useState();
useEffect(() => {
const categories = () => {
let array = [];
projects.forEach((project) => {
array.push(...project.stack);
});
const uniqueCategories = [...new Set(array.map((stack) => stack))];
setCategories(uniqueCategories);
};
return () => categories();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<FilterContainer>
<ul>
{categories && categories.map((category) => <li key={uuidv4()}>{category}</li>)}
</ul>
</FilterContainer>
);
};
export default CategoryList;
And I call the component to where it belongs.
but when I build and deploy it to Firebase it's blank
with no errors in the console.
I've tried to diagnose this issue by inserting console.log in the beginning and end of the useEffect hook and I noticed that the code wasn't getting executed..
So my question is, what do I need to search and study for? If it's a simple problem can someone point out the problem?
I've tried putting this straight into the .jsx file and also by making it as a component.
Thanks in advance!
CodePudding user response:
In development it works because react mount twice the component and doesn't work in production cause it mounts the component only one time (read react-scrict-mode). You call categories
in the function that will be executed on component's unmount phase (read comments):
useEffect(() => {
const categories = () => {
let array = [];
projects.forEach((project) => {
array.push(...project.stack);
});
const uniqueCategories = [...new Set(array.map((stack) => stack))];
setCategories(uniqueCategories);
};
// Here, if a useEffect hook returns a function
// that function will be executed when the component is being destroyed
return () => categories();
eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
To fix this, just remove the wrapper function and call your function like this:
useEffect(() => {
const categories = () => {
let array = [];
projects.forEach((project) => {
array.push(...project.stack);
});
const uniqueCategories = [...new Set(array.map((stack) => stack))];
setCategories(uniqueCategories);
};
categories();
eslint-disable-next-line react-hooks/exhaustive-deps
}, []);