Skip to content
Advertisement

Find array object by ID and return it in React

I try to fetch object vorlagen with ID 6310 from this API and want to show if property vorlageAngenommen is true or false.

The JSON object looks as follows:

API extract

My code that does not run, looks as follows (I am not sure if this is a good base at all):

import useSWR from "swr";
import "./styles.css";

const fetcher = (...args) => fetch(...args).then((res) => res.json());

const arrayFindObjectByProp = (arr, prop, val) => {
  return arr.find((obj) => obj[prop] == val);
};

export default function App() {
  const { data, error } = useSWR(
    "https://www.bfs.admin.ch/bfsstatic/dam/assets/14856203/master",
    fetcher
  );
  const specificVoting = null;

  console.log("swr error: ", error);
  console.log("swr data: ", data);

  return (
    <div className="App">

      <div style={{backgroundColor: "red"}}>
        {data ? (
          {specificVoting = arrayFindObjectByProp(data.schweiz.vorlagen, vorlagenId, '6310')}
          <h4>{specificVoting.vorlageAngenommen}</h4>
        ) : (
          <h1>loading...</h1>
        )}
      </div>

    </div>
  );
}

I created a sandbox as well that can be found here.

Any idea how I can fetch and present a specific element of an array where I know the ID?

Many thanks for your feedback in advance.

Advertisement

Answer

Your code has a few issues.

First: You should extract the value outside of the return statement

Second; You should pass on the property value as a string to arrayFindObjectByProp function

Lastly: Since the value returned is a boolean, you need to convert it into a string to display in the component

export default function App() {
  const {data, error } = useSWR(
    "https://www.bfs.admin.ch/bfsstatic/dam/assets/14856203/master",
    fetcher
  );

  console.log("swr error: ", error);
  console.log("swr data: ", data);
  const specificVoting =
    data && arrayFindObjectByProp(data.schweiz.vorlagen, "vorlagenId", "6310");
  return (
    <div className="App">
      <div style={{ backgroundColor: "red" }}>
        
        {data ? (
          <h4>{specificVoting.vorlageAngenommen.toString()}</h4>
        ) : (
          <h1>loading...</h1>
        )}
      </div>
    </div>
  );
}

working demo

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement