Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Giorgi Parunov
Giorgi Parunov

Posted on

     

One of the ways to use Context API

As you know a lot of developers replaced redux with react context feature. So I want to show you how I am using it in my products.

We will create a Todo list using context API (based on typescript).

I will use bootstrap for design._
_Image description

Final view of our code.

Let's get started!

At first, we must create our context in thecontexts folder.

TodoContext.ts

import{createContext}from"react";exportinterfaceITodo{name:string;completed:boolean;}interfaceITodoContext{data:ITodo[];updateData:Function;}exportconstTodoContext=createContext<ITodoContext>({data:[],updateData:(data:ITodo[])=>{thrownewError('updateData not implemented')}})
Enter fullscreen modeExit fullscreen mode

Here we can see that we are creating an interface for todo items, and also for todo context.

My context has two values, the first one is the data that it must contain and the second one is the function that will update the data.

After creating context we must create a provider for it.
We are creating it in theproviders folder.

TodoProvider.tsx

import{FC,ReactNode,useState}from"react";import{ITodo,TodoContext}from"../contexts/TodoContext";interfaceITodoProvider{children:ReactNode}exportconstTodoProvider:FC<ITodoProvider>=({children})=>{const[data,setData]=useState<ITodo[]>([]);constupdateData=(data:ITodo[])=>{setData(data);}return(<TodoContext.Providervalue={{data,updateData}}>{children}</TodoContext.Provider>)}
Enter fullscreen modeExit fullscreen mode

In our todo provider, we will create and append the initial state for todo data. Also, we must create a function for handling data updates and appending it to our state.

Now we can start to use our created context API in our product.

What we must do:

  • Render Todo List.
  • Create Todo Item.
  • Delete Todo Item.

So let's do it step by step

Render Todo List
Idea is to render the table with our todo data.

We will create aTodoList.tsx file in thecomponents folder.

exportconstTodoList=()=>{const{data:todoData}=useContext(TodoContext);return(<divclassName="container"><divclassName="d-flex justify-content-between"><divclassName="py-3"><h3>Todo List</h3></div></div><tableclassName="table table-striped table-dark"><thead><tr><td>Name</td><tdwidth="200">Status</td><tdwidth="150"align="right">Action</td></tr></thead><tbody>{todoData?.map((item:ITodo,index)=>(<trkey={`todo-${index}`}><td>{item.name}</td><td>{item.completed?<spanclassName="badge badge-info">Completed</span>:<spanclassName="badge badge-secondary">Not Completed</span>}</td></tr>))}</tbody></table></div>)}
Enter fullscreen modeExit fullscreen mode

Here you can see that we are using reactsuseContext hook for getting our data from context.

const {data: todoData} = useContext(TodoContext);

So we will have always up-to-date data that we are getting from
TodoContext.

Of course, it will be always empty, so we must add create functionality for it.

Lets create a simple form.

<formref={formRef}className="py-3 d-flex justify-content-between"onSubmit={handleCreate}><inputtype="text"name="name"className="form-control"/><buttontype="submit"className="btn btn-primary mx-1">Add</button></form>
Enter fullscreen modeExit fullscreen mode

We must createhandleCreate function in our component for detecting submitting in form.

const{data:todoData,updateData:updateTodoData}=useContext(TodoContext);consthandleCreate=(event:React.SyntheticEvent)=>{event.preventDefault();const{target}=eventastypeofevent&{target:{name:{value:string};}}constname=target.name.value;updateTodoData([...todoData,{name:name,completed:false}])formRef?.current?.reset();}
Enter fullscreen modeExit fullscreen mode

Here you can see that we added updateData which we are taking from our context, and using it as updateTodoData for creating and saving new todo item.

Thats it. Now on submitting form it will create and render new item in our todo list.

By the same logic we can create delete functionality also.

consthandleDelete=(name:string)=>{constpayload=todoData.filter(item=>item.name!==name)updateTodoData(payload);}
Enter fullscreen modeExit fullscreen mode

We are taking the name and filtering our array by it.
After it, we are using ourupdateTodoData function and update our array.

You can check the repositoryhere

And how you are using Context API in your applications?

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Experienced Frontend Developer with a demonstrated history of working in the information technology and services industry. Skilled in JavaScript , TypeScript, and Application Frameworks.
  • Location
    Georgia, Tbilisi
  • Work
    Senior Software Engineer at Singular
  • Joined

More fromGiorgi Parunov

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp