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
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
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"
]
}
I'm trying to implement Elasticsearch update_by_query using react button onClick.
When I click the react button it should set Elasticsearch document boolean field isCancelRun to true (index name is: run)
I would like to add the next query as a react function that will be executed with the button onClick:
curl -X POST "http://elasticsearch_ip_addr:9200/run-*/_update_by_query?pretty" -H "Content-Type: application/json" -d'
{
"script": {
"source": "ctx._source.isCancelRun = true;",
"lang": "painless"
},
"query": {
"term": {
"runId": "20220419142721270"
}
}
}
'
I implemented the next function that should be called when the button is clicked:
export function cancelRunExecution(runIdToCancel) {
fetch(`${ElasticSearch_BaseAddress}${"run-*"}/_update_by_query?pretty`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body:
`{"query":{"bool":{"must":[{"match":{"runId":"${runIdToCancel}"}}]}}},
script: {
source: "ctx._source.isCancelRun = true;",
lang: "painless"
}`
})
.then(response => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response.json();
});
}
ElasticSearch_BaseAddress = elasticsearch_ip_addr:9200/
The button implementation with onClick should execute cancelRunExecution function:
<div>
<button id="cancelRun" onClick={() => {
cancelRunExecution(props.run.runId);
var btn = document.getElementById("cancelRun");
btn.innerHTML = 'Run execution - canceled';
}}>
Cancel Run Execution
</button>
</div>
The problem:
It does not change the boolean field isCancelRun to true.
What you send is not JSON since script, source and lang are not double-quoted.
Send this payload instead:
body:
`{"query":{"bool":{"must":[{"match":{"runId":"${runIdToCancel}"}}]}}},
"script": {
"source": "ctx._source.isCancelRun = true;",
"lang": "painless"
}`
})
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",
}