I'm trying to map "historicData" and put them in the labels of chart but it gives me error,"u cannot map the undefined".
So,Error is historicData is undefined .When I console.log(historicData),there is an array data.
This is my Code.
https://github.com/Saithiha24/React-Crypto-Beast/blob/master/src/Components/CoinInfo.js
I try to solve this for 2 days still can't find the answer. Please help me.
I think the problem is that historicData is initially undefined, and while waiting for the async call to complete and give historicData a value, you get the error. I suggest you change this
const [historicData, setHistoricData] = useState();
to this
const [historicData, setHistoricData] = useState([]);
so historicData is originally an empty array instead of undefined. You can also change the definition of data likes this
const data = {
labels: historicData ? historicData.map((coin) => {
//your code
}) : []}
so that if historicData is undefined, you don't try to map, just assign an empty array to labels.
Related
What I'm trying to do is fetch an array of objects, then fetch data related to the first object in the array.
const progress = useSelector(state => state.progress);
const appInfo = useSelector(state => state.appInfo);
const {
data: steps,
isLoading: isStepsLoading,
isSuccess: isStepsSuccess
} = useGetAllStepsQuery()
const {
data: questions
} = useGetQuestionsQuery({app_id: appInfo.id, step_parameter: steps[progress.currentStepIndex].step_parameter}, {skip: isStepsLoading})
The problem I'm having is that attempting to extract the step_parameter from the steps array is throwing a Cannot read properties of undefined (reading '0') error: in other words, it's as if the useGetQuestionsQuery is being called before the useGetAllStepsQuery is finished. I've added a skip parameter to the request, per this answer, and tried various values with it (e.g. !isStepsSuccess), none of them resolve this problem. I've also tried assigning the step_parameter conditionally, like this:
step_parameter: isStepsSuccess ? steps[progress.currentStepIndex].step_parameter : ''
Which does prevent the error, but it also appears to prevent the questions call from ever being made. Any help would be appreciated!
I have run into this weird behavior which I don't know how to figure out. It involves array destructuring. I know that react renders changes on state only when a new object is passed into the setLocations function, even though it doesn't render the state it still changes the data on the state which you can see by refreshing, but here, I have made an entirely new array newLocation and have populated it with new data but it does not store the data to locations at all while destructuring the array inside setLocations works.
I do not understand what makes this happen. Can someone please provide me with a response.
Thank you and the code example is below.
const searchGeoLocation = async (event) => {
event.preventDefault();
const fetchedData = await fetch(url);
const data = await fetchedData.json();
const newLocation = [];
// This works without the for each
// newLocation.push(...data);
// setLocations(newLocation);
data.forEach(element => {
newLocation.push(element)
});
// Has the right array
console.log(newLocation);
// does not work and prints an empty array
setLocations(newLocation);
console.log(locations);
// Does Work
setLocations(...newLocation);
console.log(locations);
}
I understand why this behavior happens with the comments I got, and I am going to answer my question myself just so that people who stumble upon the same issue in the future can understand as well.
It seems changes on the state are only reflected when a re-render happens. The console.log I put in the function shows the state before the re-render takes place, so when I put the console.log function in the body, the changes are being reflected in the state.
I have set 2 arrays with useState in 2 different files:
const [filterQuery, setFilterQuery] = React.useState({
instructor: [],
material: [],
})
const [query, setQuery] = React.useState({
instructor: [],
material: [],
})
And i have this function that will update query with values from filterQuery:
const applyFilter = (filterQuery) => {
setQuery((prev) => ({
...prev,
instructor: filterQuery.instructor,
material: filterQuery.material,
}));
}
The strange behavior is when i call setFilterQuery from a different function, an example is updating filterQuery when a button is clicked
onClick = (value) => {
setFilterQuery({
...filterQuery,
instructor: value
})
}
What I expected is it will just update filterQuery, but query will magically updated with filterQuery too whereas it has no connection to the function whatsoever.
What could trigger this ? I have tried a few things, declaring a new variable first before using the setQuery :
const filter = filterQuery;
setQuery((prev) => ({
...prev,
instructor: filter.instructor,
material: filter.material,
}));
not working.
I have also tried changing the set format without the prev, using just ...query or without them and still not working.
Thank you for reading, helps appreciated.. Will provide more code info / what else I have tried if asked.
In JavaScript primitive types are passed around as values: meaning that each time a value is assigned, a copy of that value is created.
On the other side objects (including plain objects, array, functions, class instances) are references. If you modify the object, then all variables that reference that object are going to see the change.
Here what basically happens is that you are passing the reference of query to filterQuery, not the value to query that's why when you change either query or filterQuery they both get updated.
You can see more details and examples at this question's answer and difference between values and reference
I have no idea why I'm getting this error or from where is coming from because I think I'm not using that ?
I'm doing a firebase update after an user update a row from DataGrid MUI and I'm doing the update as I would normally do nothing different at all and it just jumps into that error.
I'm not sure if is an React error, JS error, Firebase error, MUI error. but I THINK is a firebase error because the path says so
This is what I was trying to do:
const [editRowsModel, setEditRowsModel] = React.useState({});
const [editRowData, setEditRowData] = React.useState({});
const handleEditRowsModelChange = React.useCallback(
(model) => {
const editedIds = Object.keys(model);
if (editedIds.length === 0) {
console.log(editRowData)
console.log(editRowData.uid)
console.log(editRowData.nombre)
console.log(editRowData.colegio)
console.log(editRowData.grado)
const temporalQuery = db.collection("usuarios").doc(user.uid).collection("estudiantes").doc(editRowData.uid);
temporalQuery.update({
nombre: editRowData.nombre,
colegio: editRowData.colegio,
grado: editRowData.grado
})
} else {
setEditRowData(model[editedIds[0]]);
}
setEditRowsModel(model);
},
[editRowData]
);
This is what the console.log shows up. I honestly don't see any error in the way I code it that's how I always do it, never had an issue before. First time I update from a nested collection though
This is how it looks in the firebase
And yes the user.uid also comes correctly
Found the issue is because the data comes with a whole string of information instead of just the value as I though it was coming.
All I had to do was to call the field + the value when I was using it.
Ej:
if I wanted the uid I had to call it editRowData.uid.value
the .doc(name) only accepts strings, so check if your user.uid is a string
I have an issue when i trying to updating the state.
here is my code:
const [todos, setTodos]= useState([])
useEffect(() => {
setTodos([
{id:1, title: '',
notes: [{id: 1, description: 'this is a simple description'}]}
])
}, [])
my goal is to add a note to the array of todos.
i try like this
const i = todos.findIndex((t) => t.id === parseInt(id));
const newArr = todos[i].notes[0].push(note);
setTasks(newArr);
but it's not working the newArr gives me the index note the new state.
Please help
Thanks in advance
if you want to get it working you can do something like below:
const newArr = todos[i].notes.push(note)
but it's not the recommended way.
The best way to add new item in to your notes array is to use object.assign or spread operator in order to not directly mutate your entire array. some thing like below:
const newArr = [...todos[i], note]
and also use this way of mutating your entire tasks array.
I think it's been well-described ar here if you want to get more information around why you should use spread operator instead of push.
I have created this which works perfectly. What you have to do is to obtain the todo id and push to its note. Here the todo state gets updated but render method is not called. In order to call the render method I have called setTodo again.