1

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.

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Shubham for your very appreciated solution and explaining me the issues I had in my code. This helped me a lot and I am getting better :-)
1

Try this:

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

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

  const item = data?.shchweiz?.vorlagen.find(
    (item) => item.vorlagenId === 6310
  );

  return (
    <div className="App">
      <div style={{ backgroundColor: "red" }}>
        {data ? (
          <>
            vorlageAngenommen value:{" "}
            {item?.vorlageAngenommen ? `true` : `false`}
          </>
        ) : (
          <h1>loading...</h1>
        )}
      </div>
    </div>
  );
}

https://codesandbox.io/s/react-array-find-object-by-prop-forked-z8lg1?file=/src/App.js:50-673

1 Comment

Thank you Dennis for your help and this working solution where I additionally could learn about developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

it seems that

{specificVoting = arrayFindObjectByProp(data.schweiz.vorlagen, vorlagenId, '6310')}

should be replaced by followed

{specificVoting = arrayFindObjectByProp(data.schweiz.vorlagen, 'vorlagenId', '6310')}

1 Comment

Thank you newbie for your feedback and your hint that helped me. I had some additional issues in my code as can be seen in the other answers.
0

i think its this line

{specificVoting = arrayFindObjectByProp(data.schweiz.vorlagen, vorlagenId, '6310')}

It should have been this way:

{specificVoting = arrayFindObjectByProp(data.schweiz.vorlagen, "vorlagenId", '6310')}

"vorlagenId" should be passed as string and not variable.

2 Comments

Thank you shaswat.dharaiya for your feedback and your hint that helped me. I had some additional issues in my code as can be seen in the other answers.
Please vote the answer if it was helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.