How to add an item to an array within context? (React typescript)

I created a context search in my application, where I have an array called "searchPosts". My goal is to send an object from a component into this array in context and thus be able to use it in other components. I would like to create a global state where my object is stored

​

context

import { createContext } from "react";

export type SearchContextType = {
    searchPost: (text: string) => void;
};

export const SearchContext = createContext<SearchContextType>(null!);

provider

import React, { useState } from "react";
import { SearchContext } from "./SearchContext"

export const SearchProvider = ({ children }: { children: JSX.Element }) => {
    const [searchPosts, setSearchPosts] = useState([]);

    const searchPost = (text: string) => {

    }

    return (
        <SearchContext.Provider value={{searchPost}}>
            { children }
        </SearchContext.Provider>
    );
}

I created this search function because in theory it should be a function for me to add the item to the array, but I don't know how I could do that.

This is the state that I have in my component called "searchPosts" that I get the object that I would like to pass to my global array. I want to pass the information from this array in this component to my global array in context

​

  const navigate = useNavigate();
  const api = useApi();

  const [searchText, setSearchText] = useState('');
  const [searchPost, setSearchPost] = useState([]);

  const handleSearch = async () => {
    const posts = await api.getAllPosts();
    const mapPosts = posts.filter(post =>         
post.title.toLowerCase().includes(searchText));
    setSearchPost(mapPosts);
  }

Posted Jan 6, 2023, 5:30 PM UTC

10
Loading comments…