Reactjs, error send data to post with axios - javascript

hi I am trying to post a form with email and password, but I have an error in the function that sends the data, that function you see in the image
action.js
import axios from 'axios';
export const createUser =(usuariosBody, callback) => {
return function(dispatch){
dispatch({type: 'CREATE_USER_REQUEST'});
axios.post('http://localhost:8080/users', usuariosBody)
.then((response)=>{
dispatch({type: 'CREATE_USER_SUCCESS', payload:response.data})
if (typeof callback === 'function') {
callback(null, response.data);
}
})
}
}
component.jsx
class LoginComponent extends Component{
constructor(props) {
super(props);
}
componentDidMount() {
}
render(){
return(
<section className="form-sign brown lighten-5">
<form onSubmit={this.handleSubmit.bind(this)}>
<input ref="email" placeholder='Email' />
<input type="password" ref="password" />
<Button type='submit' >send</Button>
</form>
</section>
)
}
handleSubmit(event) {
this.preventDefault();
const email = ReactDOM.findDOMNode(this.refs.email).value.trim();
const password = ReactDOM.findDOMNode(this.refs.password).value.trim();
// create a user object
const user = {
email,
password
};
// call the action
this.props.createUser(user, function (err, res) {
if (err) {
console.error(err);
} else {
console.log(res);
}
});
}
}
export default LoginComponent;
container.jsx
import React, {Component} from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {createUser} from '../action/action.js';
import {LoginComponent} from '../component/loginComponent.jsx';
class CreateUserContainer extends Component{
componentDidMount(){
}
render (){
return (<LoginComponent createUser={this.props.createUser} />);
}
}
function mapStateToProps(store) {
return {};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
createUser:CreateUser
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(CreateUserContainer);
thanks for your help

You are importing {CreateUser} and trying to use {createUser} in the container.jsx file.

You need to use mapDispatchToProps instead of matchDispatchToProps and also
use CreateUser in you mapDispatchToProps function since you imported it as CreateUser
class CreateUserContainer extends Component{
constructor(props) {
super(props);
}
componentDidMount(){
}
render (){
return(
<LoginComponent createUser={this.props.createUser} />
)
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
createUser:CreateUser
}, dispatch)
}
Also your class must implement the constructor to inherit the props
One more thing is that your handleSubmit function in LoginComponent is not bound
class LoginComponent extends Component{
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
You can also try and console.log(this.props) in your LoginComponent to see if it receives the createUser function

Related

My React function being passed down as props is not being invoked

I am trying to re-render the page based on a button click. I have the function updateCowList which calls setState() in my app component. The handleClick logic is in my newCow component which handles the button and the text input.
The console.logs() that I am seeing are 'fire', but I am not seeing the 'after' console.log(), nor am I seeing any of the logs within my updateCowList function in App.
How can I get my updateCowList function to run? I have tried calling it in all sorts of ways, destructuring props, etc.
Here is my App:
import React from 'react';
import CowList from './CowList.jsx';
import CowListEntry from './CowListEntry.jsx';
import axios from 'axios';
import SearchDB from './searchDB.js';
import NewCow from './NewCow.jsx';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cows: []
}
// this.updateCowList = this.updateCowList.bind(this);
}
componentDidMount() {
SearchDB()
.then((res) => {
this.setState({cows: res.data})
}, (err) => {
console.log(err);
});
}
updateCowList(cow) {
console.log('update cow list is running')
oldCows = [...this.state.cows];
newCows = oldCows.push(cow);
console.log('new cows be4 set state', newCows);
this.setState({cows: newCows});
console.log('new cows after set state', newCows);
}
render() {
return (
<div>
<CowList cows={this.state.cows}/>
<NewCow props={this.updateCowList}/>
</div>
)
}
}
export default App;
here is my NewCow component:
import React from 'react';
import axios from 'axios';
class NewCow extends React.Component {
constructor(props) {
super(props);
this.state = {
entry: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
let split = this.state.entry.split(', ')
console.log(split)
axios.post('http://localhost:3000/api/cows', {
name: split[0],
description: split[1]
})
.then(res => { console.log('fire', res.data);
this.props.updateCowList(res.data);
console.log('after')
})
.catch(err => 'error submitting cow :( mooooo');
}
handleChange (event) {
this.setState({entry: event.target.value})
}
render () {
return (
<div className='newCowForm'>
<input className='form-control' type='text' onChange={this.handleChange} value={this.state.entry} placeholder={'name, description'} />
<button onClick={this.handleClick} className='newCowButton'>Create new cow</button>
</div>
)
}
}
export default NewCow;
<NewCow props={this.updateCowList}/>
should be :
<NewCow updateCowList={this.updateCowList}/>

Can i pass component state to HoC?

Is there any way to send data from the component's state to HoC?
My component
import React, { Component } from 'react';
import withHandleError from './withHandleError';
class SendScreen extends Component {
contructor() {
super();
this.state = {
error: true
}
}
render() {
return (
<div> Test </div>
)
}
};
export default withHandleError(SendScreen)
My HoC component:
import React, { Component } from 'react';
import { ErrorScreen } from '../../ErrorScreen';
import { View } from 'react-native';
export default Cmp => {
return class extends Component {
render() {
const { ...rest } = this.props;
console.log(this.state.error) //// Cannot read property 'error' of null
if (error) {
return <ErrorScreen />
}
return <Cmp { ...rest } />
}
}
}
Is there any way to do this?
Is the only option is to provide props that must come to the SendScreen component from outside??
A parent isn't aware of child's state. While it can get an instance of a child with a ref and access state, it can't watch on state updates, the necessity to do this indicates design problem.
This is the case for lifting up the state. A parent needs to be notified that there was an error:
export default Cmp => {
return class extends Component {
this.state = {
error: false
}
onError() = () => this.setState({ error: true });
render() {
if (error) {
return <ErrorScreen />
}
return <Cmp onError={this.onError} { ...this.props } />
}
}
}
export default withHandleError(data)(SendScreen)
In data you can send the value you want to pass to HOC, and can access as prop.
I know I answer late, but my answer can help other people
It is very easy to do.
WrappedComponent
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import HocComponent from './HocComponent';
const propTypes = {
passToHOC: PropTypes.func,
};
class WrappedComponent extends Component {
constructor(props) {
super(props);
this.state = {
error: true,
};
}
componentDidMount() {
const {passToHOC} = this.props;
const {error} = this.state;
passToHOC(error); // <--- pass the <<error>> to the HOC component
}
render() {
return <div> Test </div>;
}
}
WrappedComponent.propTypes = propTypes;
export default HocComponent(WrappedComponent);
HOC Component
import React, {Component} from 'react';
export default WrappedComponent => {
return class extends Component {
constructor() {
super();
this.state = {
error: false,
};
}
doAnything = error => {
console.log(error); //<-- <<error === true>> from child component
this.setState({error});
};
render() {
const {error} = this.state;
if (error) {
return <div> ***error*** passed successfully</div>;
}
return <WrappedComponent {...this.props} passToHOC={this.doAnything} />;
}
};
};
React docs: https://reactjs.org/docs/lifting-state-up.html
import React, { Component } from 'react';
import withHandleError from './withHandleError';
class SendScreen extends Component {
contructor() {
super();
this.state = {
error: true
}
}
render() {
return (
<div state={...this.state}> Test </div>
)
}
};
export default withHandleError(SendScreen)
You can pass the state as a prop in your component.

object can't get method or property 'getCars'

i'm working on react-redux intermidiate..but i don't know what's going wrong
on this project
hera i have creacted the searchbar for getting car details..and the file is created as 'search.js'...you can see here..
search.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getCars } from '../actions';
import { bindActionCreators } from 'redux';
class Search extends Component{
constructor(props){
super(props);
this.state = {
keyword:''
}
}
searchCars = (event) => {
event.preventDefault();
this.props.getCars(this.state.keyword)
}
handleChange = (event) => {
this.setState({
keyword:event.target.value
})
}
componentDidMount(){
console.log(this.state);
}
render(){
return(
<div className="main_search">
<form onSubmit={this.searchCars}>
<input type="text" value={this.state.keyword} onChange = {this.handleChange} />
</form>
</div>
)
}
}
// mapStateToProps
// mapDispatchToProps
function mapDispatchToProps(dispatch){
return bindActionCreators({getCars}, dispatch)
}
export default connect(null,mapDispatchToProps)(Search);
and i think error comes from here about getCars..which is described below as s 'index.js'...you can see here
index.js
const URL_ROOT = 'http://localhost:3004'
export default function getCars(keywords){
const request = fetch(`${URL_ROOT}/carsIndex?q=${keywords}`,
{method:'GET'})
.then(response => response.json())
return{
type:'SEARCH_CARS',
payload:request
}
}
and the error looks like this..
and error showing in bundle.js file
so try to fix it and help me...
Please change your mapDispatchToProps method as
const mapDispatchToProps = (dispatch)=> (
bindActionCreators(getCars, dispatch)
)

How to call/execute method/function from another component react

I will want to know, if is possible call or execute a method or function from another component.
I would like to run asynchronously the function that is the tableInformacion.js, which has a request get, but after the call of thepost request is made that I have in address.js.
address.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
import {getSolarDayInformation} from './tableInformation.js';
import '../styles/main.css';
class AddressInput extends Component{
constructor(){
super();
this.state = {
address: "",
api:"http://maps.google.com/maps/api/geocode/json?address=",
direccion: "",
latitud: "",
longitud:""
};
}
render(){
return(
<div>
<form>
<input type="text"
value={this.state.address}
onChange={this.updateAdress.bind(this)}
placeholder="Escriba la direccion"/>
<button onClick={this.getAddressGeo.bind(this)}>Consultar</button>
</form>
<ul className="None-Style">
<li><label>Direccion:</label>{this.state.direccion}</li>
<li><label>Latitud:{this.state.latitud}</label></li>
<li><label>Longitud:{this.state.longitud}</label></li>
</ul>
</div>
)
}
updateAdress(event){
this.setState({
address: event.target.value
});
}
getAddressGeo(e){
e.preventDefault();
const apiUrl = this.state.api + this.state.address;
request.post(apiUrl).then((res) => {
const direccionCompleta = res.body.results[0].formatted_address;
const Latitud = res.body.results[0].geometry.location.lat;
const Longitud = res.body.results[0].geometry.location.lng;
this.setState({
direccion: direccionCompleta,
latitud: Latitud,
longitud: Longitud
})
})
.catch((err) => {
console.log(err.message);
});
getSolarDayInformation();
}
}
export default AddressInput;
tableInformacion.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
class TableConsumeInformation extends Component{
constructor(){
super();
this.state = {
apiSolarInformation: 'https://asdc-arcgis.larc.nasa.gov/cgi-bin/power/v1beta/DataAccess.py?request=',
parameters:'execute&identifier=SinglePoint&parameters=ALLSKY_SFC_SW_DWN&',
startDate:'0101&',
endDate:'1231&',
comunity: 'userCommunity=SSE&tempAverage=DAILY&outputList=JSON,ASCII&',
latitudePlace:'lat=',
longitudePlace:'&lon=',
anonymous:'&user=anonymous'
};
}
render(){
return(
<div>
<h2>Information Energy</h2>
<table></table>
</div>
);
}
getSolarDayInformation(){
apiSolarUrl = 'https://asdc-arcgis.larc.nasa.gov/cgi-bin/power/v1beta/DataAccess.py?request=execute&identifier=SinglePoint&parameters=ALLSKY_SFC_SW_DWN&startDate=20170101&endDate=20171231&userCommunity=SSE&tempAverage=DAILY&outputList=JSON,ASCII&lat=11.373&lon=-72.253&user=anonymous';
request.get(apiSolarUrl).then((req, res) => {
console.log(res.body);
});
}
}
export default TableConsumeInformation;
I assume you are talking about the getSolarDayInformation function in this case.
In your case here, it looks like the easiest thing to do would be to refactor your function into its own file and import it into all the places its needed. There is no reason for it to be a object method as it has no dependency on the object state.
You could create a helper functions file, something like
helper.js
export const getSolarDayInformation = () => {
...
}
Then, import the method in your other file(s)
import {getSolarDayInformation} from 'path/to/your/file';

Why aren't my todo items rendering with Redux?

I'm doing a simple redux / react todo app. I can't get the todo items to show up. I'm able to console.log the data, but can't get it to appear. What am I doing wrong?
I separated the files, here is my app.js:
import React, { Component } from 'react';
import Todos from './todos';
import TodoList from "./todo_list";
export default class App extends Component {
render() {
return (
<div>
<Todos />
<TodoList/>
</div>
);
}
}
Here is the container Todos:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addTodo } from '../actions/index';
class Todos extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
}
addTodo(e) {
e.preventDefault();
this.props.addTodo(this.state.text);
this.setState({
text: ''
});
}
updateValue(e) {
this.setState({text: e.target.value})
}
render() {
return (
<div>
<form onSubmit={(e) => this.addTodo(e)}>
<input
placeholder="Add Todo"
value={this.state.text}
onChange={(e) => {
this.updateValue(e)
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({addTodo}, dispatch);
}
export default connect(null, mapDispatchToProps)(Todos);
Here is the TodoList:
import React, {Component} from 'react';
import {connect} from 'react-redux';
class TodoList extends Component {
render() {
return (
<ul>
{ this.props.todo.map((tod) => {
return <li key={tod.message}>{ tod.message }</li>
})}
</ul>
);
}
}
function mapStateToProps({ todo }) {
console.log({ todo });
return { todo };
}
export default connect(mapStateToProps)(TodoList);
Reducer:
import { ADD_TODO } from '../actions/types';
export default function(state=[], action) {
switch(action.type) {
case ADD_TODO:
return [ action.payload.message, ...state ]
}
return state;
}
And action
import { ADD_TODO } from './types';
const uid = () => Math.random().toString(34).slice(2);
export function addTodo(message) {
const action = {
id: uid(),
message: message
};
return {
type: ADD_TODO,
payload: action
};
}
This is what I get from the console.log({todo});
Here is my reducers/index:
import { combineReducers } from 'redux';
import TodosReducer from './reducer_addTodo';
const rootReducer = combineReducers({
todo: TodosReducer
});
export default rootReducer;
It's because there's a disconnect between your TodoList and reducer. TodoList, when mapping, expects each todo to have a message prop, but your reducer, when returning next state, only includes the message in the state array, not an object with the message property:
case ADD_TODO:
return [ action.payload.message, ...state ]
Instead, do not just put the message string in the next state's array, put in the whole object:
case ADD_TODO:
return [ action.payload, ...state ]
Now every single element in the todo array will be an object and have a message and id property. Also, try using an always unique expression for key -- it really shouldn't be the todo message, nor the id you supplied because it's using Math.random which both have a possibility of keys being the same.

Categories

Resources