array of objects map is not a function - reactjs

I'm new to React, I'm pulling an API, which is filled with an array of objects.
When trying to map it I get following error: "Uncaught TypeError: benchmarkData.map is not a function"
While I get the error, it actually does the job (when I log it I get the asked result), it just prevents loading the other elements.
This is how my API looks:
[
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "412",
"DEGEMAT": "235",
"DEGEMGW": "97.7",
"DEGEMMB": "3.39",
"DEGEMNV": "64.1",
"DEGEMSD": "13.2",
"DEGEMVD": "71.3",
"DEJAART": "2022",
"DELTMCE": "-",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "436",
"DEGEMAT": "233",
"DEGEMGW": "120.1",
"DEGEMMB": "3.38",
"DEGEMNV": "64.2",
"DEGEMSD": "13.2",
"DEGEMVD": "71.4",
"DEJAART": "2022",
"DELTMCE": "ALL",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "22",
"DEGEMAT": "213",
"DEGEMGW": "99.9",
"DEGEMMB": "3.23",
"DEGEMNV": "64.9",
"DEGEMSD": "12.7",
"DEGEMVD": "72.8",
"DEJAART": "2022",
"DELTMCE": "BBC",
"DEWEENR": "1"
}
]
This is my React code:
useEffect(() => {
if (benchmarkData) {
setSupplierHasData(true);
let loadingplaceFilter = [];
const loadingPlaces = [];
benchmarkData.map(item => { //!start of requested question code
if(item.type === "drlvbmk") {
loadingPlaces.push(item.DELPLCE, item.DELTMCE, item.DEELTCE)
}
}
); //!end of requested question code
console.log(loadingPlaces);
const uniqueLoadingplaces = [];
loadingPlaces.map((item) => {
var findItem = uniqueLoadingplaces.find((x) => x === item);
if (!findItem) uniqueLoadingplaces.push(item);
});
console.log('uniqueloadingplaces', uniqueLoadingplaces);
setFilters({
...filters,
loadingplaces: loadingplaceFilter,
});
setFilterData(true);
}, [benchmarkData]);
Pulling the api:
useEffect(() => {
const fetchBenchmarkData = async () => {
setFetchNewData(false);
console.log('current user active id :', suppliersState.suppliers.activeID, "current user active uuid: ", suppliersState.suppliers.activeUUID);
try {
await axios
.get(
`https://bpg-ap.ddev.site/jsonapi/benchmarking_get_data?supplierid=${suppliersState.suppliers.activeID}&date_from=1&date_to=2022`
)
.then(res => {
setBenchmarkData(res.data);
console.log('BENCHMARKINGRESULTAAT : ', res.data);
});
} catch(error) {
setSupplierHasData(false);
setChartData({});
console.log(error);
}
};
if (benchmarkData === null) {
console.log('useEffect fired, fetch benchmarkData', benchmarkData);
fetchBenchmarkData();
}
}, [benchmarkData, suppliersState.suppliers.activeID]);
Logging benchmarkData results in:
I hope anyone can help me to solve this problem

Related

React does not update nested state using my setter

I'd like to update a react state (the "app" variable) object dynamically. The state has several properties, one of them is a nested object ("app.error" object). There is a kind of setter function ("setAppData") which takes any number of [existing key]: new value pairs of the state as parameter, create a new object and it should update the state according to "temp" object.
It works as intended when I want to update "app.error" using hard-coded variable or any other "app" properties, when I try to update the "app.error" using my setter function, it does not update.
const initialAppData: IAppData = {
error: {} as IFrontEndError,
interfaceTheme: UI_THEME.LIGHT,
};
function AppProvider(props: any) {
const [app, setApp] = useState<IAppData>(initialAppData);
useMemo(() => {
window.addEventListener("error", (event) => {
errorHandler({
colno: event.colno,
filename: event.filename,
lineno: event.lineno,
message: event.message,
});
});
}, []);
const errorHandler = (event: IFrontEndError) => setAppData({error: { ...event }});
const setAppData = (newValue: TUpdateAppData) => {
let key: keyof IAppData;
let temp = getAppData();
for (key in newValue) {
if (
!Object.prototype.hasOwnProperty.call(app, key) ||
!Object.prototype.hasOwnProperty.call(newValue, key)
)
continue;
temp = {
...temp,
[key]: newValue[key],
};
}
setApp({ ...temp, error: { ...temp.error } });
};
const getAppData = () => ({ ...app });
}
Using static update (it works as intended):
const setAppData = () => {
let temp = getAppData();
temp.error = {
colno: 1,
lineno: 1,
message: "asd",
filename: "asd"
}
setApp({ ...temp, error: { ...temp.error } });
};
The structure of the "temp" objects before passing the spreaded copy to the state setter are exactly the same. "temp" object before spreading, triggered by event:
{
"error": {
"colno": 11,
"filename": "http://127.0.0.1:5173/src/components/Debug.tsx?t=1667134926865",
"lineno": 29,
"message": "Error: asd"
},
"interfaceTheme": "light-theme"
}
getAppData() after error event:
{
"error": {},
"interfaceTheme": "light-theme"
}
"temp" object before spreading using hard-coded value:
{
"error": {
"colno": 1,
"lineno": 1,
"message": "asd",
"filename": "asd"
},
"interfaceTheme": "light-theme"
}
getAppData() after execution using hard-coded value:
{
"error": {
"colno": 1,
"lineno": 1,
"message": "asd",
"filename": "asd"
},
"interfaceTheme": "light-theme"
}
What is that I don't notice?
edit: sources of the project:
https://github.com/gazsop/magus_shared
https://github.com/gazsop/magus_react

Can't use the data from API when app just starts

My data is undefined when the app is started but after the refresh, the data comes perfectly.
For startup
It gives me [Unhandled promise rejection: TypeError: Object.entries requires that input parameter not be null or undefined]
But after the refresh, the data comes perfectly and everything working.
This is part of my data
Object {
"attributes": Object {
"htmlName": null,
"id": 0,
"items": Array [
Object {
"htmlName": "r_1",
"name": "m2 (Brüt)",
"numeric": true,
"options": Object {},
"order": 0,
"required": true,
},
Object {
"htmlName": "r_2",
"name": "m2 (Net)",
"numeric": true,
"options": Object {},
"order": 0,
"required": true,
},
Object {
"htmlName": "r_164",
"name": "Arsa Alanı (m2)",
"numeric": true,
"options": Object {},
"order": 0,
"required": true,
},
Object {
"htmlName": "a_137",
"name": "Oda Sayısı",
"numeric": false,
"options": Object {
"12": "1+0",
"13": "1+1",
"14": "1.5+1",
"15": "2+0",
"16": "2+1",
"17": "2.5+1",
"18": "2+2",
"19": "3+1",
"20": "3.5+1",
"21": "3+2",
"22": "4+1",
"226": "0+1",
"23": "4.5+1",
"24": "4+2",
"25": "4+3",
"26": "4+4",
"27": "5+1",
"28": "5+2",
"29": "5+3",
"30": "5+4",
"31": "6+1",
"32": "6+2",
"33": "6+3",
"34": "7+1",
"35": "7+2",
"36": "7+3",
"37": "8+1",
"38": "8+2",
"39": "8+3",
"40": "8+4",
"41": "9+1",
"42": "9+2",
"43": "9+3",
"44": "9+4",
"45": "9+5",
"46": "9+6",
"47": "10+1",
"48": "10+2",
"49": "10 Üzeri",
},
"order": 0,
"required": true,
},
api.js
export const getData = function () {
return axios
.get(
"blabla",
{
headers: {
Authorization: `blabla`,
},
}
)
.then((json) => {
if (json && json.status === 200) {
//console.log(json);
return json.data;
}
})
.catch((e) => {
console.log(e);
});
};
App.js
const [data, setData] = useState({});
const [roomValue, setRoomValue] = useState(null);
const [roomCount, setRoomCount] = useState([]);
const [isFocus, setIsFocus] = useState(false);
useEffect(() => {
getDataFunc();
//setDropdown(data.attributes.items[3].options);
}, []);
const getDataFunc = async () => {
const res = await getData();
//console.log(res);
setData(res);
console.log(data);
};
function setDropdown(query) {
const response = query;
try {
const entries = Object.entries(response);
const tempArray = [];
for (let i = 0; i < entries.length; i++) {
var key;
var value;
(key = entries[i][0]), (value = entries[i][1]);
tempArray.push({ key: value, value: key });
}
setRoomCount(tempArray);
//console.log(roomCount);
} catch (error) {
//console.log(error);
}
}
How can I fix that ?
Add a seperate useEffect to check wheather the data has been set and then only set the dropdown values
useEffect(() => {
getDataFunc();
}, []);
useEffect(() => {
if(data && data.attributes?.items[3]){
setDropdown(data.attributes.items[3].options);
}
}, [data]);
const getDataFunc = async () => {
const res = await getData();
//console.log(res);
setData(res);
console.log(data);
};
It seems like the error is caused by the attributes property being empty when you try to access it. But when you assign them one by one then it loads because the data is loaded per nested property before assigning it to the variable. Means it hasn't fully loaded yet
const response = data.attributes.items[3].options;
It outputs an error because attributes is undefined. So it's not an object, therefore, attributes.items is considered invalid
// sample
const data = {
/* attributes: {
items: {
1: {
options: 'option1'
},
2: {
options: 'option2'
},
3: {
options: 'option3'
}
}
} */
}
const specificData = data.attributes.items[3].options
console.log(specificData) //
So one solution would be using the optional chaining operator to avoid the error, it's just basically a question mark (?) after the object you are trying to access.
The response would be then 'undefined'. That way even if the attributes is empty or not, data will be assigned to the response constant then you can just add some more checking outside of that.
// sample
const data = {
/* attributes: {
items: {
1: {
options: 'option1'
},
2: {
options: 'option2'
},
3: {
options: 'option3'
}
}
} */
}
const specificData = data.attributes?.items[3].options
console.log(specificData) // outputs undefined instead of an error
Let me know if this works btw. maybe you could provide the actual api or maybe a sample api endpoint so we could test it directly. Or maybe the full code?
I've encoutered this before though I'm not 100% sure this is all I've done. But for the error I'm sure the optional chaining operator will prevent it
Try calling getData inside an async function and wait for the process to complete like this in your App.js
const [data, setData] = useState([]);
const [roomCount, setRoomCount] = useState([]);
useEffect(() => {
getDataFunc()
}, []);
const getDataFunc = async() => {
await getData(setData);
const response = data;
console.log(response);
const entries = Object.entries(response);
const tempArray = [];
for (let i = 0; i < entries.length; i++) {
var key;
var value;
(key = entries[i][0]), (value = entries[i][1]);
tempArray.push({ key: value, value: key });
}
setRoomCount(tempArray);
console.log(roomCount);
}
note: The best practice is not to directly pass the setData function to getData api call instead return the response from api and assign the response in main code like below
const response = await getData();
setData(response)
From what I see, your data.attributes has undefined value.
Please double-check everything, it is technically impossible to get data directly if data.attributes is undefined

How to Set States Inside Loop React Nextjs

I have a functions that should update data provided by the user. But due to some strange reason its only updating first value of quizzes. Its not updating Topic value and when adding second value to quizzes it revert backs to 1st value.
Data
[
{
"Topic": [ "Biology", "Introduction to Biology" ],
"Question": "Example of micro molecule is:",
"Quizzes" : ["2022 Biology Geek", "General Knowledge"]
},
{
"Question": "Pepsin enzyme works in;"
}
]
Code
const [finalData, setFinalData] = useState({
TOPIC: [],
QUIZZES: []
})
const setData = () => {
const ei = userSelectedData.topic;
const yr = userSelectedData.quiz
selectedDocsID.forEach(doc => {
fetchDoc("ques", doc)
.then((response) => {
const TField = response["Topic"]
const QField = response["Quizzes"]
const newTs = new Set([...finalData.TOPIC]);
const newQs = new Set([...finalData.QUIZZES]);
//If Topic Field Does not Exist
if (TField == undefined) {
newTs.add(doc);
setFinalData({ ...finalData, EI: Array.from(newTs) })
}
//If Topic Field Exist But Don't have Requried Value
else if (TField.includes(ei) != true) {
newTs.add(doc);
setFinalData({ ...finalData, EI: Array.from(newTs) })
}
//If Quiz Field Does not Exist
if (QField == undefined) {
newQs.add(doc);
setFinalData({ ...finalData, YR: Array.from(newQs) })
}
//If Quiz Field Exist But Don't have Requried Value
else if (QField.includes(yr) != true) {
newQs.add(doc);
setFinalData({ ...finalData, YR: Array.from(newQs) })
}
})
});
}
<Button onClick={() => setData()}>Update Data</Button>
Current Result
//Displaying Results by console.log inside useEffects Hook
{
"TOPIC": [],
"QUIZZES": [
"2022 Biology Geek",
"General Knowledge"
]
}
//After Few Seconds
{
"TOPIC": [],
"QUIZZES": [
"2022 Biology Geek"
]
}
Expected Result
{
"TOPIC": ["Biology"],
"QUIZZES": [
"2022 Biology Geek",
"General Knowledge"
]
}

How to push to object in React Native?

I know I'm probably overlooking something obvious, but when trying to push to an existing object, nothing happens. It will log up to "Makes it here".
const storeData = async (todo) => {
try {
const getCurrentTodos = await AsyncStorage.getItem('todos');
let currentTodos = JSON.parse(getCurrentTodos);
if(currentTodos) {
currentTodos = [];
}
console.log('Makes it here', currentTodos)
currentTodos.push(todo);
console.log('Does not make it here', currentTodos)
} catch(e) {
// save error
}
console.log('Makes it here.')
}
This is the currentTodos obj
Object {
"description": "none",
"title": "Test 1",
}
This is the todo obj
Object {
"description": "none",
"title": "Test 2",
}

Cypress - Condition depending on json list

I have a json list containing some several hundreds of entries. I want to check whether the list contains a specific entry.
I tried using .contains as a chainer, but this is not accepted by Cypress:
const permission_list = require('../../fixtures/permissions/permissions_admin.json')
describe('Test plan creator for Administrator', () => {
it('create a test plan', () => {
cy.get(permission_list[0].granted_permissions).then((list) => {
if (list.contains('dyna'))
{cy.log('Yes')}
else
{cy.log('No')}
})
})
})
This leads to the error message:
TypeError
list.contains is not a function
{edit} I also tried .includes instead of .contains with the same result
Just for information, this is what the json list looks like (the list I am interested is the list "granted permissions")
[
{
"name": "administrator",
"title": "Administrator",
"description": "",
"is_external": "0",
"granted_permissions": [
"dyna",
"jobcards",
...
...
],
"denied_permissions": [],
"inherited_roles": []
}
]
You can use the Jquery inArray method.
describe('Test plan creator for Administrator', () => {
it('create a test plan', () => {
cy.get(permission_list[0].granted_permissions).then((list) => {
if (Cypress.$.inArray('dyna', list) != -1) {
cy.log('Yes') //dyna found
} else {
cy.log('No')
}
})
})
})

Resources