I’ve been working on a project where I need to render a list of medicines from an API. Here is a brief overview of my steps:
-
Created a Search Bar: The search bar fetches the output using the provided API.
-
Render Cards Based on API Data: The API returns a length based on the search value, which I use with the
map
method to create cards. -
Available Forms Rendering: The API contains different available forms such as:
{ "available_forms": [ ["Tablets"], ["capsule", "oral"], ["Tablets", "injection"], ["capsule"] ] } Based on the available_forms length, I used the map method to render each form in a card using <li> tags. Example: Card 1: Tablets Card 2: Capsule Oral Card 3: Tablets Injection Click Behavior Issue: I added an onClick method to the <li> tag. When clicking Card 1 Tablet, it also selects Card 3 Tablet when using Context API. Note: I don't want this behavior. If I click Card 1 Tablet, only that should be selected, not other Tablets. Desired Behavior: When using useState in the local file, only the clicked card element is selected, which is the correct behavior. Here is the sample API response for reference: { "data": { "saltSuggestions": [ { "id": 487, "salt": "Paracetamol+Paracetamol", "salt_frequency": 19, "available_forms": [ "Tablet" ], "most_common": { "Form": "Tablet", "Strength": "300mg+700mg", "Packing": "10 tablet sr" }, "salt_forms_json": { "Tablet": { "300mg+700mg": { "10 tablet sr": { "2863": [ { "pharmacy_id": 3, "selling_price": 50 }, { "pharmacy_id": 2, "selling_price": 44 } ], "31440": null, "75341": null } } } } } ] } }
My Code (Summary)
Here is the relevant part of my code that demonstrates the issue:
import React, { useState, useContext } from 'react'; // Assuming MedicineContext is set up properly import { MedicineContext } from './MedicineContext'; const MedicineList = () => { const { medicines } = useContext(MedicineContext); const [selectedForm, setSelectedForm] = useState(null); const handleClick = (form) => { setSelectedForm(form); }; return ( <div> {medicines.map((medicine, index) => ( <div key={index}> <h3>{medicine.salt}</h3> <ul> {medicine.available_forms.map((form, idx) => ( <li key={idx} onClick={() => handleClick(form)}> {form.join(' ')} </li> ))} </ul> </div> ))} </div> ); }; export default MedicineList;
The Issue
When using Context API, clicking on Card 1 Tablet also selects Card 3 Tablet. I only want the clicked item to be selected. When I switch to using
useState
in a local file, the selection works as expected.
Desired Solution
I need help to achieve the behavior where clicking on an item only selects that specific item without affecting others when using Context API.
Shiva is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.