I wonder if anyone can help?
I have a list of base users that I fetch from an API and render to the page via the Dashboard
component.
I want to create another list, in a separate route/component (Favorites
), that allows for a user to create a personalized user list, like a list of favorites.
At the moment, I am stuck on what to now do with the array of favorites. How do I get the array sharable from Dashboard to Favorites? Could I create a context? But how would that look?
Below is my dashboard component that contains the base list and the favorites.
A sandbox is https://codesandbox.io/s/affectionate-frost-8zuzw1?file=/src/components/Dashboard/Dashboard.js:304-370 for anyone interested
const Dashboard = () => {
const navigate = useNavigate();
const [favourites, setFavourites] = useState([]);
const { data: usersData } = useFetchUsers();
const onClickHandlerAdd = (user) => {
setFavourites([...favourites, user]);
};
return (
<div>
<button
onClick={() => {
navigate("/myList");
}}
>
Navigate To My List
</button>
{usersData?.map((user) => (
<>
<div key={user.id}>
<p>{user.id} </p>
<p>{user.name}</p>
<button onClick={() => onClickHandlerAdd(user)}>Add</button>
</div>
</>
))}
Another List
{favourites?.map((user) => (
<>
<div key={user.id}>
<p>{user.id} </p>
<p>{user.name}</p>
</div>
</>
))}
</div>
);
};
export default Dashboard;
>Solution :
You can create a context in App.js
with createContext
, create the state and pass it into your components with the Provider
of your context like so:
export const FavContext = createContext();
const App = () => {
const [favourites, setFavourites] = useState([]);
return (
<FavContext.Provider value={{ favourites, setFavourites }}>
<HashRouter>
<Routes>
<Route path={"/"} element={<Dashboard />} />
<Route path={"/favorites"} element={<Favorites />} />
</Routes>
</HashRouter>
</FavContext.Provider>
);
};
Now you can access the objects passed into the components by importing the context and extract them using useContext
:
import { FavContext } from "../../App";
const Favorites = () => {
const navigate = useNavigate();
const { favourites } = useContext(FavContext);
return (
<div>
<button
onClick={() => {
navigate("/");
}}
>
Navigate To Dashboard
</button>
{favourites?.map((user) => (
<>
<div key={user.id}>
<p>{user.id} </p>
<p>{user.name}</p>
</div>
</>
))}
</div>
);
};