Closed devYuraKim closed 1 week ago
createContext
.ContextProvider
function, including all the related states
and returning
<Context.Provider value={...}>{children}</Context.Provider>
useContext
to access and return the context.{ ContextProvider, useContext }
state
from other contexts like const { searchQuery } = useSearchContext()
.function createRandomPost() {
return {
title: `${faker.hacker.adjective()} ${faker.hacker.noun()}`,
body: faker.hacker.phrase(),
};
}
const PostContext = createContext();
function PostProvider({ children }) {
const [posts, setPosts] = useState(() =>
Array.from({ length: 30 }, () => createRandomPost())
);
const { searchQuery } = useSearchContext();
// Derived state. These are the posts that will actually be displayed
const searchedPosts =
searchQuery.length > 0
? posts.filter((post) =>
`${post.title} ${post.body}`
.toLowerCase()
.includes(searchQuery.toLowerCase())
)
: posts;
function handleAddPost(post) {
setPosts((posts) => [post, ...posts]);
}
function handleClearPosts() {
setPosts([]);
}
return (
<PostContext.Provider
value={{
posts: searchedPosts,
onAddPost: handleAddPost,
onClearPosts: handleClearPosts,
}}
>
{children}
</PostContext.Provider>
);
}
function usePostContext() {
const context = useContext(PostContext);
return context;
}
export { PostProvider, usePostContext };
Completely lost. I know that I need to return functions somewhere that have access to the
value
, but that's it.