I’m making an api call to get the information of certain companies linked by the id of a client. Lets suppose that the api call is the next:
useEffect(() => {
(async () => {
await fetch('/api/myapi_where=clientId=' + idClient, {
method: "GET",
headers: {
"Accept": "application",
"Content-type": "application/json"
},
}).then(response => {
const hasInfo = response.json();
hasInfo.then(setInfo => {
console.log(setInfo)
})
})
.catch()
})()
},[])
On the response, the api has a promise, where lives the required information; that’s why I need to transform the response on json format, an use "then". So, on the console log i see that there’s more than one registers linked to the client. Per example, i have the next answer:
[{id:1, idClient: 2, name: "Company 1", creationDate: "2023-01-11"}]
[{id: 6, idClient: 2, name: "Company 2", creationDate: "2023-02-27"}]
[{id: 25, idClient: 2, name: "Company 5", creationDate: "2023-03-10"}]
As you can see, on the database exists 3 different rows linked to a single client (idCLient 2). So, here’s my question: how can I merge all this 3 different rows in a single array of objects? What i wanna do is return the information on a single array to create a list with map. Something like this:
const singleArray = [{id:1, idClient: 2, name: "Company 1", creationDate: "2023-01-11"}, {id: 6, idClient: 2, name: "Company 2", creationDate: "2023-02-27"}, {id: 25, idClient: 2, name: "Company 5", creationDate: "2023-03-10"}]
And the list:
return (
singleArray.map((info, index) => {
return(
<>
<li key={index} className="class-name">
<p>{info.name}</p>
</>
)
})
)
I’ve already try with: const someTest = setInfo.concat(setInfo);
and I receive:
[{id:1, idClient: 2, name: "Company 1", creationDate: "2023-01-11"}, {id:1, idClient: 2, name: "Company 1", creationDate: "2023-01-11"}, {id:1, idClient: 2, name: "Company 1", creationDate: "2023-01-11"}]
On a certain way, it’s working, but not as I’m expecting. I receive 3 different arrays with the same information repeated 3 times (or X times, depending the length of the rows). Can you help me to fine the best practice to receive correctly the information as I need, please? I’ve been searching but cannot find something that realy helps me, or the correct way to get close to the solution. I’m working on react.
Thanks in advance
2
Answers
I assume the setInfo is array. In that case you can use the below method.
It will convert your array into array of objects.