I'm trying to setup Django Rest Framework w/ React with the end goal of sending a POST request through a form submission.
As a proof of where things are at, this POST request does execute when the button is clicked.
const App = () => {
const [postData, setPostData] = useState('Click to post');
const postRequest = (payload) => {
fetch('http://127.0.0.1:8000/api/task-create/',
{method:'POST',
headers:{'content-type':'application/json',
'X-CSRFToken':getCookie('csrftoken')
},
body:JSON.stringify(payload)
})
.then( response => {setPostData('post request succsesful')})
};
return( <button onClick={postRequest({title:'first post'})}>{postData}</button> );
};
Now given the above, I'd like to use a form so content can be dynamically sent from the browser to DRF API.
function App() {
const [fields, setFields] = useState({});
const handleFieldChange = (event) => {
setFields({...fields, element: event.target.value});
}
const handleSubmit = (event) => {
event.preventDefault();
};
return(
<form onSubmit={handleSubmit}>
<input
onChange={handleFieldChange}
value={fields.element} />
<input
type='submit'
value='submit'/>
</form>
)
}
Should I add the postRequest function to handleFieldChange, handSubmit, or elsewhere?