skip to Main Content

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


  1. const data = [
      [{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"}],
      [{id:2, idClient: 3, name: "Company 2", creationDate: "2023-01-11"}],
      [{id: 7, idClient: 3, name: "Company 3", creationDate: "2023-02-27"}],
      [{id: 26, idClient: 3, name: "Company 6", creationDate: "2023-03-10"}]
    ];
    
    function App() {
    
      const clientData = [];
      for (let i = 0; i < data.length; i++) {
        const record = data[i][0];
        const clientIndex = clientData.findIndex((r) => r.idClient === record.idClient);
        if (clientIndex > -1) {
          clientData[clientIndex].data.push(record);
        } else {
          clientData.push({
            idClient: record.idClient,
            data: [record],
          });
        }
      }
    
      return (
        <div>
        {
          clientData.map((client) => {
            return (
              <div className="client-record">
                <span>Client ID: <b>#{client.idClient}</b></span>
                <span>Works at</span>
                {
                  client.data.map((record) => {
                    return (
                      <span>{record.name}</span>
                    );
                  })
                }
              </div>
            );
          })
        }
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    .client-record {
      display: flex;
      flex-direction: column;
      margin: 10px 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>
    Login or Signup to reply.
  2. I assume the setInfo is array. In that case you can use the below method.
    It will convert your array into array of objects.

    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 => {
                        const result = setInfo.reduce((acc,item) => {
                          acc = [...acc, item[0]];
                          return acc;
                          },[])
                          console.log(result);
                       })
                    })
                    .catch()
                    })()
                },[])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search