skip to Main Content

I have used Params to get the url of the page that I linked to it before and it was ok to this stage, but then I can’t set items accordingly.

const {id} = useParams();
const [item, setItem] = useState([]);

useEffect(() => {
  fetch("https://.../V1/homepage/consts_list_homepage")
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      const selectedItem = data.data.find((item,index) => index + 1 === id);
      setItem(selectedItem);
    })
    .catch((error) => console.log(error));
}, []);

I should mention that as there is no id in my items data, I’ve used index+1 instead of id. It rendered the id but I wondered why the item doesn’t set. I receive Loading… for <h2 className="drname"> {item ? `${item.Fname} ${item.Lname}` : "Loading..."} </h2>
I have change the route path to "…./:id" too
I would be so thankful if you help me solve the problem

2

Answers


  1. Chosen as BEST ANSWER

    Miracle of asking question in stackoverflow, it solved after 2 hours strugelling with it. Just change it: const selectedItem = data.data[id - 1];


  2. I would do few things here:

    1 – Check that "id" really contains what it’s supposed to

    2 – Why are you saving an array in item instead of the element? I expect to have an item, so that you need to change several things:

    // Item is initialized as null
    const [item, setItem] = useState(null);
    ...
    // The find method will return an array with only 1 item, so that take the first element of the array as selectedItem
    const [selectedItem] = data.data.find((item,index) => index + 1 === id);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search