Home > Software engineering >  Getting the correct data from selected item using useParams
Getting the correct data from selected item using useParams

Time:11-03

I am trying to get data only from specific item selected, but unfortunately I don't know how to approach this.

This is what I tried:

My route looks like this:

<Router>
  <Switch>
    <Route exact path="/explore">
      <ExploreCard closetItems={closetItems} />
    </Route>
    <Route path="/explore/:id">
      <ExploreDetail
        closetItems={closetItems}
        setClosetItems={setClosetItems}
      />
    </Route>
  </Switch>
</Router>

And the fetch from API:

const [closetItems, setClosetItems] = useState([]);

useEffect(() => {
  const getClosets = async () => {
    try {
      const response = await axios.get(
        "https://api.npoint.io/eb35d003cd0c1991c6aa"
      );
      const closet = response.data;
      setClosetItems(closet);
    } catch (error) {
      console.log(error);
    }
  };
  getClosets();
}, []);

Then I am mapping through the items like so:

{closetItems.map((list) => (
  <div key={list.id}>
    <h4>
      Name: <Link to={`/explore/${list.id}`}>{list.name}</Link>
    </h4>
  </div>
))}

Here what happens using code above:

  1. I get to the correct path (if I choose an item with ID of 2 then path is /explore/2)
  2. Path /explore/2 shows detailed data of all items not only of id=2

Here how it looks like:

const ExploreDetails = ({ closetItems, setClosetItems }) => {
  const { id } = useParams();

  return (
    {closetItems
      // .filter((list) => list.id === id)
      .map((list) => (
        <div key={list.id}>
          <h2>Name: {list.name}</h2>
          <h4>Category: {list.email}</h4>
        </div>
      ))}

How can I fetch data only of selected item with id = 2 ?

CodePudding user response:

Adding from the answer of Javad Masoudian, if you want to return only the element that matches some condition, you can also use Array#find then use it like so:

//...
const params = useParams();

const list = closetItems.find(({ id }) => id === parseInt(params.id));

//...
return (
  <>
    <h2>Name: {list.name}</h2>
    <h4>Category: {list.email}</h4>
  </>
);

This way you don't get back an array but instead the object itself that you can use directly.

CodePudding user response:

All params of URL are as string type.

You can use parseInt() method to convert to integer type.

const ExploreDetails = ({ closetItems, setClosetItems }) => {
  const { id } = useParams();
   return (
           {closetItems
              .filter((list) => list.id === parseInt(id))
              .map((list) => (
                <div  key={list.id}>
                    <h2>Name: {list.name}</h2>
                    <h4>Category: {list.email}</h4>
                </div>
    ))}
  • Related