Last active
August 23, 2023 12:40
-
-
Save EmmanuelObua/0f8e9f11bb1719ea65e0bc7d15dae040 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import { v4 as uuidv4 } from 'uuid'; | |
import { TaskConsumer } from './TaskContext'; | |
/*This is a component that controls the input elements within the forms on subsequent user input, | |
* i.e, every state mutation will have an associated handler function. | |
*/ | |
function TaskForm() { | |
/*This is a title state to store the user input for submission*/ | |
const [title, setTitle] = useState(''); | |
const addTask = (e, dispatch) => { | |
e.preventDefault(); /*Prevent default to avoid page reloading when a form is submitted*/ | |
/*Check if the title state is not empty and dispatch the action with the payload then reset the title state*/ | |
if (title.trim() !== '') { | |
dispatch({ type: 'ADD_TASK', payload: { id: uuidv4(), title } }); | |
setTitle(''); | |
} | |
}; | |
return ( | |
<TaskConsumer> | |
{({ dispatch }) => ( | |
<form onSubmit={(e) => addTask(e, dispatch)}> | |
<div className="d-flex flex-column flex-sm-column justify-content-center align-items-center"> | |
<input type="text" placeholder="Enter task" value={title} onChange={e => setTitle(e.target.value)}/> | |
<button className="mt-2 btn btn-sm btn-success" type="submit">Add Task</button> | |
</div> | |
</form> | |
)} | |
</TaskConsumer> | |
); | |
} | |
export default TaskForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment