How to POST data from this.state? - javascript

I'm trying to use this.state in a POST call with Axios, and I can't understand why it isn't working. I tried to connect (getting a "bind () is not a function" error) and setState, but nothing seems to work . I can't find any good solution for this problem, follow the code below, thanks for your help in advance!
import ReactDOM from 'react-dom';
import axios from 'axios';
class AccountSettings extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
projects: "Loading...",
};
}
componentDidMount() {
fetch("/../api/****/account/projects")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
projects: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
saveProjects(event) {
axios.post('/../api/****/account/projects/save',{
projects: this.state.projects,
})
.then()
.catch();
event.preventDefault();
}
handleOnChange(event) {
this.setState({
projects: event.target.value
})
}
render() {
return (
<form method="post" onSubmit={this.saveProjects}>
<label htmlFor="projectsInput">My projects</label>
<textarea className="form-control" id="projectsInput" rows="3" aria-describedby="projectsInputHelp"
name="projectsInput" value={this.state.projects}
onChange={(event) => this.handleOnChange(event)} />
<small id="projectsInputHelp" className="form-text text-muted">
Add every project on a new line.<br/><br/>
</small>
<button type="submit" className="btn btn-primary">
Save projects
</button>
</form>
)
}
}
ReactDOM.render(<AccountSettings />, document.getElementById("account-settings"));```

Binding works for me this.saveProjects=this.saveProjects.bind(this); and if somehow binding fails then you can always use arrow functions in class components.

I'm doing this:
let data = Object.keys(this.state.fields).map(key => encodeURIComponent('formName['+key+']') + '=' + encodeURIComponent(this.state.fields[key])).join('&'))
fetch('....', {
method: "POST",
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json, text/javascript, */*',
'X-Requested-With': 'XMLHttpRequest' <--- if needed for php framework isXmlHTTPRequest()
}
})
.then( response => response.json() )
.then( json => {
console.log(json);
})
.catch(error => console.log(error))

Related

React: Form Submit how to pass multiple row data?

I am getting the data from api. I am displaying Feature ID, DisplayOrder textbox in the rows. User can change the Display Order value in the multiple rows. How to update the information using Post API? I am passing one value FeatureID and DisplayOrder in form submit. Please help to pass all the values that are changed(FeatureID, DisplayOrder) in form submit. If suppose FeatureID 11 and FeatureID 13 Display order changes, then form submit needs to pass these information only.
{"FeatureID":"11","DescriptionText":"Travel","FeatureText":Feature2,"DisplayOrder":"1","Date":"08/30/2011","FeatureName":"Research"},
{"FeatureID":"12","DescriptionText":"Sport","FeatureText":Feature3,"DisplayOrder":"2","Date":"08/30/2011","FeatureName":"Research"},
{"FeatureID":"13","DescriptionText":"Art","FeatureText":Feature4,"DisplayOrder":"3","Date":"08/30/2011","FeatureName":"Research"}]
import React from "react";
export class EditFeatures extends React.Component {
constructor(props) {
super(props);
this.state = {
FeatureID: "",
DisplayOrder: "",
DescriptionText: "",
FeatureText: "",
Feature: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.DisplayFeatures();
}
DisplayFeatures() {
fetch(REQUEST_URL, { "Content-Type": "application/xml; charset=utf-8" })
.then((response) => response.json())
.then((data) => {
this.setState({
Feature: data,
loading: false,
});
});
}
handleSubmit(event) {
event.preventDefault();
const FeatureID = this.state.FeatureID;
const DisplayOrder = this.state.DisplayOrder;
const data = {
FeatureID,
DisplayOrder,
};
fetch(REQUEST_URL, {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error))
.then((response) => console.log("Success", data));
window.location.href = "/";
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<table>
<tbody>
{this.state.Feature.map((item, index) => {
return [
<tr key={item.FeatureID}>
<td>
<input
type="text"
id={item.FeatureID}
name="DisplayOrder"
value={item.DisplayOrder}
onChange={(ev) => {
const newFeature = this.state.Feature.map((f) => {
if (f.FeatureID == ev.target.id) {
f.DisplayOrder = ev.target.value;
}
return f;
});
this.setState({ Feature: newFeature });
}}
/>
</td>
<td>{item.DescriptionText}</td>
<td>{item.FeatureTex}</td>
</tr>,
];
})}
</tbody>
</table>
<button type="submit" name="submit">
Update
</button>
</form>
</div>
);
}
}
export default Edit_Features;
The answer is simple, just sort Feature array on DisplayOrder in handleSubmit like this:
import React from "react";
export class EditFeatures extends React.Component {
constructor(props) {
super(props);
this.state = {
FeatureID: "",
DisplayOrder: "",
DescriptionText: "",
FeatureText: "",
Feature: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.DisplayFeatures();
}
DisplayFeatures() {
fetch(REQUEST_URL, { "Content-Type": "application/xml; charset=utf-8" })
.then((response) => response.json()) // you passed Content-Type: "application/xml" as request header but here you use response.json, remove Content-Type header if server API returns json
.then((data) => {
this.setState({
Feature: data.map((feature) => ({ ...feature, changed: false })),
loading: false,
});
});
}
handleSubmit(event) {
event.preventDefault();
const FeatureID = this.state.FeatureID;
const DisplayOrder = this.state.DisplayOrder;
const Feature = this.state.Feature;
const data = {
FeatureID,
DisplayOrder,
Feature, // this is how you pass an array to server, how will the server deserialize this depends on the framework used there
};
const self = this;
fetch(REQUEST_URL, {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error))
.then((response) => {
/**
* sort manipulates the array so we clone the Feature array before sorting it
* we pass comparator function to sort so that we sort on DisplayOrder
*/
const newFeature = [...this.state.Feature];
newFeature.sort((f1, f2) => f2.DisplayOrder - f1.DisplayOrder);
self.setState({ Feature: newFeature });
});
window.location.href = "/"; // ok why does this exist?!!
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<table>
<tbody>
{this.state.Feature.map((item) => {
return [
<tr key={item.FeatureID}>
<td>
<input
type="text"
id={item.FeatureID}
name="DisplayOrder"
value={item.DisplayOrder}
onChange={(ev) => {
// this is the proper way to update an element inside an array
const newFeature = [...this.state.Feature];
// I prefer === over == to avoid errors
const featureIndex = newFeature.findIndex(
(f) => f.FeatureID === ev.target.id
);
newFeature[featureIndex].DisplayOrder =
ev.target.value;
this.setState({ Feature: newFeature });
}}
/>
</td>
<td>{item.DescriptionText}</td>
<td>{item.FeatureTex}</td>
</tr>,
];
})}
</tbody>
</table>
<button type="submit" name="submit">
Update
</button>
</form>
</div>
);
}
}
export default EditFeatures;
this way when you click button submit, if the POST request to the server succeeds, the table will be updated according to DisplayOrder.
Note
If the request to the server fails for any reason the table won't be updated, if you don't care about the response of the server just sort the Feature array outside the .then before issuing the request.

How to send data to another page in ReactJS

Here I have a problem in ReactJS, in the POST fetch section in NewCases.jsx. There will generate Data i.e. app_uid, then I want to send app_uid data from NewCases.jsx to DNNewCases.jsx, but I don't know how.
This is the Full Script:
NewCases.jsx
import React, { Component, Fragment } from 'react';
import './NewCases.css'
import user2 from '../../images/user2.png';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import DNNewCases from '../DynaformCases/DNNewCases';
class NewCases extends Component {
constructor(props) {
super(props)
this.state = {
token: sessionStorage.getItem("access_token"),
username: sessionStorage.getItem("username"),
user_role: '',
allcases: [],
inMemoryCases: [],
showProcess: [],
dataSess: [],
app_uid: '',
dataselanjutnya: '',
search: '',
}
this.getDetailCase = this.getDetailCase.bind(this);
this.searchData = this.searchData.bind(this);
}
componentDidMount() {
if (window.sessionStorage.getItem("access_token") === null) {
this.props.history.push('/');
}
fetch('https://bpm.*************.or.id/api/1.0/************/extrarest/session-id', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
dataSess: responseJson,
});
});
fetch("https://bpm.***********.or.id/api/1.0/***********/extrarest/login-user", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
}
}).then(result => result.json()).then(resultJSON => {
this.getUserRole(resultJSON.uid);
})
fetch('https://bpm.**************.or.id/api/1.0/************/case/start-cases', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson[0]);
this.setState({
allcases: responseJson,
inMemoryCases: responseJson,
});
});
}
getUserRole = (uid) => {
fetch("https://bpm.***********.or.id/api/1.0/************/user/" + uid, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
}
}).then(result => result.json()).then(resultJSON => {
if (resultJSON.usr_role == "PROCESSMAKER_ADMIN") {
this.setState({ user_role: 'Administrator' })
} else if (resultJSON.usr_role == "PROCESSMAKER_OPERATOR") {
this.setState({ user_role: 'Operator' })
} else if (resultJSON.usr_role == "PROCESSMAKER_MANAGER") {
this.setState({ user_role: 'Manager' })
}
})
}
getDetailCase(pro, tas) {
fetch("https://bpm.***************.or.id/api/1.0/************/cases/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
showProcess: responseJson,
});
this.state.app_uid = (this.state.showProcess.app_uid);
});
}
searchData = (event) => {
this.setState({ search: event.target.value })
const searchData = this.state.inMemoryCases.filter(
data => {
let lowerCase = (data.pro_title).toLowerCase()
let searchLowerCase = this.state.search.toLowerCase()
return lowerCase.indexOf(searchLowerCase) > -1;
}
);
this.setState({ allcases: searchData });
}
render() {
return (
<Fragment>
<div className="background-nya">
<div className="header">
<Link style={{ textDecoration: 'none' }} to="/menu">
<p className="headerLabel-fix"> ********** </p>
</Link>
<p className="headerLabelUser"> {this.state.username} </p>
<p className="headerLabelPass"> {this.state.user_role} </p>
<img className="userIcon" src={user2} />
</div>
<p className="titlePage"> PROCESS LIST </p>
<div className="form-search">
<input type="text" value={this.state.search} onChange={this.searchData} placeholder="search"></input>
</div>
<br />
{
this.state.allcases.map((process) => {
{ this.getDetailCase(process.pro_uid, process.tas_uid) }
return (
<Fragment>
<Link
to={{
pathname: "/dynaform",
state: this.state.app_uid
}}
>
<div key={process.pro_uid} className="caseList" onClick={this.alertShow}>
{process.pro_title}
</div>
</Link>
</Fragment>
)
})
}
</div>
</Fragment>
)
}
}
export default NewCases;
DNNewCases.jsx
import React, { Component, Fragment } from 'react';
import user2 from '../../images/user2.png';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Iframe from 'react-iframe'
class DNNewCases extends Component {
constructor(props) {
super(props)
this.state = {
username: sessionStorage.getItem("username"),
token: sessionStorage.getItem("access_token"),
dataSess: [],
}
}
componentDidMount() {
if (window.sessionStorage.getItem("access_token") === null) {
this.props.history.push('/');
}
fetch('https://bpm.**********.or.id/api/1.0/**********/extrarest/session-id', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
dataSess: responseJson,
});
});
}
render() {
return (
<Iframe url= {'https://bpm.************.or.id/***********/en/neoclassic/cases/open?APP_UID=&DEL_INDEX=1&action=EDIT&sid=' + this.state.dataSess}
width="100%"
height="100%"
display="block"
position="fixed" />
)
}
}
export default DNNewCases;
Hopefully I can find a solution here. Thank you very much
I would suggest using "react-redux".
With mapDispatchToProps and some actions, you could save the new data in a reducer, then you could access the data with mapStateToProps.
Links above provide some examples and I personally recommend youtube tutorials from techsith.
you can use props when navigating between components,
Have a look at this, to pass data between router link
if not for a better solution, try using Redux.
youtube tutorial click here
I suggest the usage of withRouter
export default withRouter(props => <NewCases {...props} />);
From ReactTraining Docs:
You can get access to the history object’s properties and the closest
's match via the withRouter higher-order component. withRouter
will pass updated match, location, and history props to the wrapped
component whenever it renders.
Once you get access to your history, make use of this snippet to reroute:
this.props.history.push(`/someRoute`);
Simply call this snippet in your setState callback after your API call & after you've set the correct state to app_uid. As I stated in my comment, it appears you are directly mutating your state. I highly suggest to set the new app_uid inside the setState function
As a side note: I do not see your Route configurations. This answer assumes you've at least set up your client-side-routing on your original code base.

how to fetch data using assignment or function in react

I have a component where I fetch data:
here is my code :-
class HomePage extends Component{
constructor(props) {
super(props)
this.state = {
eminem: []
}
}
url = "https://deezerdevs-deezer.p.rapidapi.com/search?q=";
componentDidMount = () => {
fetch(this.url + "eminem", {
"method": "GET",
"headers": {
"Accept": "application/json",
"x-rapidapi-host": "deezerdevs-deezer.p.rapidapi.com",
"x-rapidapi-key": [key]
}
})
.then((response) => response.json())
.then((responseObject) => {
console.log(responseObject);
this.setState({ eminem : responseObject})
}
)
.catch((err) => {
this.setState({ error: true });
console.log('An error occucred:', err);
})
}
render(){
return(
<>
<div className="col-12 col-md-9 offset-md-3 mainPage">
<div className="row">
<div className="col-9 col-lg-11 mainLinks d-none d-md-flex">
TRENDING
PODCAST
MOODS AND GENRES
NEW RELEASES
DISCOVER
</div>
</div>
<div className="row">
<div className="col-10">
<div id="rock">
<h2>Eminem</h2>
<div className='row'>
{ this.state.eminem.data.forEach(item => {
<div className='col-3'>{item.title}</div>
})}
</div>
</div>
</div>
</div>
</div>
</>
)
}
}
But I've got an error: Expected an assignment or function call and instead saw an expression no-unused-expressions. I can't understand what I've missed. And give me advice what do I have to understand in react to avoid such mistakes. Cause I'm a newcomer in react world and wanna understand all the concepts.
hi can just replace your componentDidMount handler with below one and try if it's solving your problem or not because what I think that you use inappropriate formate for defining that method
componentDidMount () {
fetch(this.url + "eminem", {
"method": "GET",
"headers": {
"Accept": "application/json",
"x-rapidapi-host": "deezerdevs-deezer.p.rapidapi.com",
"x-rapidapi-key": [key]
}
})
.then((response) => response.json())
.then((responseObject) => {
console.log(responseObject);
this.setState({ eminem : responseObject})
}
)
.catch((err) => {
this.setState({ error: true });
console.log('An error occucred:', err);
})
}
and also return the element from the loop like this
{ this.state.eminem.data.map(item => <div className='col-3'>{item.title}</div>)}
First : As your initial state looks like this :
this.state = {
eminem: []
}
If you are getting your data inside responseObject.data then change this
this.setState({ eminem : responseObject})
To :
this.setState({ eminem : responseObject.data })
Second :
Because you are not returning anything from loop, first you need to change forEach to map and then you need to return JSX from it.
Change this :
{
this.state.eminem.data.forEach(item => {
<div className='col-3'>{item.title}</div>
})
}
To :
{
this.state.eminem.map(item => { // <--- map
return <div className='col-3'>{item.title}</div> // <--- Return
})
}
OR (shorter version)
{
this.state.eminem.map(item => <div className='col-3'>{item.title}</div>)
}

Set input value automatically on a fetch request

I present my problem to you
In the following code, I'm trying to retrieve phone numbers from an API and then show them in a Card; in each card, I have a different number which is displayed
and also in each card, I have an input field to enter the phone number which I obtained before.
My problem is that I don't want to fill in the input manually with the recovered number.
So basically I would like to start my function without having to fill in this field manually.
Do you have any idea how to do this?
I tried to simplify the code so that it is as clear as possible
Thanks for your help Neff
import React, { Component } from 'react';
import { CardText, Card,Row, Col, CardTitle, Button } from 'reactstrap';
import axios from 'axios'
const entrypoint = process.env.REACT_APP_API_ENTRYPOINT+'/api';
class AdminPage extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
message: {
to: '',
body: 'hola amigo :)'
},
submitting: false,
error: false
};
this.onHandleChange = this.onHandleChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
this.setState({ submitting: true });
fetch('/api/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.message)
})
.then(res => res.json())
.then(data => {
if (data.success) {
this.setState({
error: false,
submitting: false,
message: {
to: '',
body: ''
}
});
} else {
this.setState({
error: true,
submitting: false
});
}
});
}
// rest of the component
onHandleChange(event) {
const name = event.target.getAttribute('name');
this.setState({
message: { ...this.state.message, [name]: event.target.value }
});
}
getRandom = async () => {
const res = await axios.get(
entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}
render() {
let datas = this.state.data.map(datass => {
const status = JSON.parse(localStorage.getItem("validated-order")||"{}")[datass.id];
return (
<div>
< Col sm="12" key={datass.id} className="wtfFuHereIsForOnlyBackGroundColorForCol12Nice">
<div key="a">
<Card body className="yoloCardBody">
<CardText> Téléphone {datass.phone}</CardText>
<form
onSubmit={this.onSubmit}
className={this.state.error ? 'error sms-form' : 'sms-form'} >
<div>
<input
type="tel"
name="to"
id="to"
value={this.state.message.to}
onChange={this.onHandleChange}
/>
</div>
<Button className="buttonForLancerMaybe" type="submit" disabled=
{this.state.submitting}>SMS</Button>
</form>
</Card>
</div>
</Col>
</div>
)
})
return (
<div> <div>
<div>
{datas}
</div>
</div>
</div>
<div className="box">
</div>
</div>
)
}
}
export default AdminPage
So I guess this little change in your code will help you, separating the logic and making a new component for your form section would be your solution. say we have a component called "SmsForm" so first, you need to import it in your current component:
import SmsForm from "../SmsForm/Loadable";
and then you pass your phone number as a prop to this SmsForm like this:
let datas = this.state.data.map(datass => {
const status = JSON.parse(localStorage.getItem("validated-order") || "{}")[datass.id];
return (
<div>
< Col sm="12" key={datass.id} className="wtfFuHereIsForOnlyBackGroundColorForCol12Nice">
<GridLayout className="GridlayoutTextOnlyForGridOuiAndHeigthbecauseHeigthWasBug" layout={layout} cols={12} rowHeight={30} width={1200}>
<div key="a">
<Card body className="yoloCardBody">
<CardText> Téléphone {datass.phone}</CardText>
<SmsForm phone={datass.phone}/>
</Card>
</div>
</GridLayout>
</ Col>
</div>
)
})
and SmsForm would be sth like this:
import React from 'react';
...
export class SmsForm extends React.Component {
constructor(props) {
super(props);
this.state = {
message: {
to: props.phone,
body: 'hola amigo :)'
},
submitting: false,
error: false
};
this.onHandleChange = this.onHandleChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
this.setState({ submitting: true });
fetch('/api/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.message)
})
.then(res => res.json())
.then(data => {
if (data.success) {
this.setState({
error: false,
submitting: false,
message: {
to: '',
body: ''
}
});
} else {
this.setState({
error: true,
submitting: false
});
}
});
}
// rest of the component
onHandleChange(event) {
const name = event.target.getAttribute('name');
this.setState({
message: { ...this.state.message, [name]: event.target.value }
});
}
render() {
return (
<form
onSubmit={this.onSubmit}
className={this.state.error ? 'error sms-form' : 'sms-form'} >
<div>
<input type="tel" name="to" id="to" value={datass.phone} onChange={e => this.onHandleChange(e, e.target.value)}/>
</div>
<Button className="buttonForLancerMaybe" type="submit" disabled=
{this.state.submitting}>SMS</Button>
</form>
);
}
}
export default SmsForm;

ReactJS & Redux access state "constructor" from another file

I'm just trying to post a data everything working fine if I put the fetch function in the same file but when I moved it to another file it shows cannot read property, I've tried this.props instead of this.state, how can I connect this file to constructor()
scr/component/layout.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import { fetchUsers, postUsers } from '../actions/usersAction';
class Layout extends Component {
constructor(){
super()
this.state = {
name: '',
age: ''}
}
onUserUpdate(filed, event){
console.log('onUserUpdate: ' + filed + '==' + event.target.value);
if (filed == 'name') {
this.setState({
name: event.target.value
})
return
}
if (filed == 'age') {
this.setState({
age: event.target.value
})
return
}
}
componentDidMount() {
this.props.fetchUsers();
}
render() {
const { act } = this.props;
const fetchUserss = act.users.map(d => <tr key={d.id}><td>{d.name}</td><td>{d.age}</td></tr>);
return (
<div className="App">
<label>
name:
</label>
<input type="text" name="name" onChange={this.onUserUpdate.bind(this, 'name')} placeholder="Enter Name"/>
<label>
age:
</label>
<input type="text" name="age" onChange={this.onUserUpdate.bind(this, 'age')} placeholder="enter username"/>
<button type="simpleQuery" onClick={this.props.postUsers.bind(this)}>Add News</button>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{fetchUserss}
</tbody>
</table>
</div>
);
}
}
function mapStateToProps(state) {
return {
act: state.users,
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({fetchUsers, postUsers}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(Layout);
src/actions/userAction.js
export const fetchUsers = (data) =>{
return{
type: "USERS",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
}
};
export const postUsers = (event) =>{
let users = {
name: this.state.name,
age: this.state.age
}
return{
type: "USERS_POST",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(users),
})
.then(res => res.json())
}
};
src/reducers/userReducer.js
const initalState = {
fetching: false,
fetched: false,
users: [],
error: null
};
export default function(state=initalState, action) {
let newState = Object.assign({}, state);
switch(action.type){
case "USERS_PENDING":{
return {...state, fetching: true,loading: false,}
}
case "USERS_FULFILLED":{
return {...state, fetching:false, fetched: true, users: action.payload,}
}
case "USERS_REJECTED":{
return {...state, fetching: false, error: action.payload,}
}
case "USERS_POST_PENDING":{
return {...state, fetching: true,}
}
case "USERS_POST_FULFILLED":{
return newState;
}
case "USERS_POST_REJECTED":{
return {...state, fetching: false, error: action.payload,}
}
default:
return state;
}
}
Please let me know if I miss out any information.
If this has already been asked, I would greatly appreciate if you are able to point me in the right direction.
Thank you so much!
You need to pass that data to your postUsers() function.
<button
type="simpleQuery"
onClick={() => this.props.postUsers(this.state.name,this.state.age)}
>Add News</button>
Then in your postUsers() function should take in those parameters:
export const postUsers = (name, age) => ({
type: "USERS_POST",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
age,
}),
})
.then(res => res.json())
});
We cannot access state outside of a component. You can pass the state variables are params to the postUsers function.
<button type="simpleQuery" onClick={this.props.postUsers(this.state.name,this.state.age)}>Add News</button>
And in your postUsers function
export const postUsers = (name,age) =>{
let users = {
name: name,
age: age
}
return{
type: "USERS_POST",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(users),
})
.then(res => res.json())
}
};
I can see that you have tried to bind a scope to an arrow function. You cannot do that. Arrow functions do not have a scope.
Instead, you should write a normal function.
either,
let postUsers = function() {};
or
function postUsers(){}
In other words this inside an arrow function is always inherited from the parent function. So in your case, this is not undefined, but it is not the this you expect.

Categories

Resources