Hello I have a question I am making app with Firebase and React. The problem is that I want to have comment array but it is empty when the item is created. How can I solve this problem and have an empty array and then update this array after adding comments.
There is a lot of code.
const onSubmitHandler = (e: React.FormEvent): void => {
e.preventDefault();
if (user?.displayName) {
const recipe: Recipe = {
username: user.displayName,
title: title,
type: type,
description: description,
id: Math.random(),
time: time,
ingredients: ingredients,
stars: Math.floor(Math.random() * 6) 1,
steps: steps,
comments: [],
};
dispatch(recipeAction.addRecipe(recipe));
dispatch(sendData(recipe));
navigate("/");
}
};
Redux action
export const fetchRecipes = () => {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
dispatch(uiAction.isLoading(true));
const getRecipes = async () => {
const response = await fetch(
*FIREBASE API*
);
const data = response.json();
return data;
};
try {
const data = await getRecipes();
console.log(data);
if (data) {
for (const key of Object.keys(data)) {
dispatch(recipeAction.replaceRecipes(data[key]));
}... other not needed code.
Redux slice
replaceRecipes(state, action: PayloadAction<Recipe>) {
const fetchedRecipe = action.payload;
state.recipes.push(fetchedRecipe);
},
CodePudding user response:
Why won't it save an empty array?
I don't have so much knowledge so I am just explaining it in java.
Now coming to the point. Now, when you create a new empty array like this:
List array = new ArrayList<>();
its size is 0. And, 0 can in other words be said null for an empty array. Now, firebase ignores null or 0 sized array as it had nothing to display in the console.
Then what should I do?
It is not a hard thing to do that. Now, in your case, because there is not such key in the database, it will give null and then you try using it and then an exception. This is what every developer wants to prevent. So the solution can be to store a boolean
in the database with the other keys to check if a data has the array or not. When the post is just created, there are no comments. You can set it to false
. Now, when a user add's a comment, set it to true
.
Now when fetching the comments, first check if the boolean
is true or not. If true, fetch the comments. Or else just ignore.
Code?
As mentioned, I have no used React JS
so much so can't provide the code. But I hope that you will be able to do it as you have already done so much of it by yourself.
Happy coding