Reputation: 36673
I have a simple React/Spring Boot application where I want to populate a dropdown based on what's returned from an API call (a list of names, e.g "o1", "o2", "o3").
It can fetch and list the names as follows:
const templateOptionsTemp = await (await fetch(API_HOST + `/api/templates/`, {
credentials: 'include'
})).json();
templateOptionsTemp.map((templateName) =>
console.log("templateName: " + templateName)
);
Now, I just need to create a json object based on the name that looks like this:
{ key: 'o1', text: 'opt 1', value: 'o1'}
and add it to the array to be used as a dropdown, which is currently like this:
const templateOptions = [
{ key: 'o1', text: 'opt 1', value: 'o1' },
{ key: 'o2', text: 'opt 2', value: 'o2' },
{ key: 'o3', text: 'opt 3', value: 'o3' },
]
So the code would have to be something like this:
const tempArray = []
templateOptionsTemp.map((templateName) =>
const obj = {
'key': templateName,
'value': templateName,
'text': templateName
}
templateOptionsTemp.push(obj);
);
this.setState(templateOptions: tempArray);
But, I'm getting a syntax error on the above code - apparently you can't add more than one statement to the "map" function. The error is saying the "," operator is expected. If I add brackets, the error message says a return value is expected.
How do I get this to work? I just need to populate the templateOptions in the app's state.
Upvotes: 1
Views: 1032
Reputation: 2677
When lambda's require multiple lines, or return an object, they must be wrapped with {}
to denote their contents, and use return
. Like this:
const tempArray = templateOptionsTemp.map((templateName) => {
return { key: templateName, value: templateName, text: templateName };
});
this.setState({templateOptions: tempArray});
Braces are also needed when you call setState.
Also the '
marks around keys inside your object are fine, but not needed. It is exactly the same to exclude them, just less code to write (although you will still need them if your keys are not valid javascript identifiers).
Upvotes: 2