Failed to Compile: 'movies' is not defined (React) - javascript

I'm getting this error message in a react app when I'm attempting to search for a movie and return a response of an array of movies.
src/App.js
Line 42:9: 'movies' is not defined no-undef
Line 42:19: 'movies' is not defined no-undef
Here is src/App.js:
import React from 'react';
import './App.css';
import unirest from 'unirest';
import Movie from './movie';
import Search from './search';
class App extends React.Component {
state = {
movies: []
}
sendRequest = (title) => {
const req = unirest("GET", "https://movie-database-imdb-alternative.p.rapidapi.com/");
req.query({
"page": "1",
"r": "json",
"s": title
});
req.headers({
'x-rapidapi-host': 'movie-database-imdb-alternative.p.rapidapi.com',
'x-rapidapi-key': 'my_api_key'
});
req.end((res) => {
if (res.error) throw new Error(res.error);
const movies = res.body.Search;
this.setState({movies});
console.log(res.body);
});
}
render() {
return (
<div className="App">
<header className="App-header">
{
movies && movies.length ? this.state.movies.map((movie) => {
return <Movie {...movie}/>
})
: null
}
<Search handleSendRequest={this.sendRequest}/>
</header>
</div>
);
}
}
export default App;
I'm not sure why it's saying 'movies' is undefined, I've set it as part of state in the beginning of the class itself. It seems like the req.end function is not accessing the state object for some reason?

Either you have to spread the state in render or use this.state.movies.
Using Destructuring
import React from 'react';
import './App.css';
import unirest from 'unirest';
import Movie from './movie';
import Search from './search';
class App extends React.Component {
state = {
movies: []
}
sendRequest = (title) => {
const req = unirest("GET", "https://movie-database-imdb-alternative.p.rapidapi.com/");
req.query({
"page": "1",
"r": "json",
"s": title
});
req.headers({
'x-rapidapi-host': 'movie-database-imdb-alternative.p.rapidapi.com',
'x-rapidapi-key': 'my_api_key'
});
req.end((res) => {
if (res.error) throw new Error(res.error);
const movies = res.body.Search;
this.setState({movies});
console.log(res.body);
});
}
render() {
const {movies} = this.state; // Use Destructuring
return (
<div className="App">
<header className="App-header">
{
movies && movies.length ? this.state.movies.map((movie) => {
return <Movie {...movie}/>
})
: null
}
<Search handleSendRequest={this.sendRequest}/>
</header>
</div>
);
}
}
export default App;
Or access state
import React from 'react';
import './App.css';
import unirest from 'unirest';
import Movie from './movie';
import Search from './search';
class App extends React.Component {
state = {
movies: []
}
sendRequest = (title) => {
const req = unirest("GET", "https://movie-database-imdb-alternative.p.rapidapi.com/");
req.query({
"page": "1",
"r": "json",
"s": title
});
req.headers({
'x-rapidapi-host': 'movie-database-imdb-alternative.p.rapidapi.com',
'x-rapidapi-key': 'my_api_key'
});
req.end((res) => {
if (res.error) throw new Error(res.error);
const movies = res.body.Search;
this.setState({movies});
console.log(res.body);
});
}
render() {
return (
<div className="App">
<header className="App-header">
{ // Use this.state to access movies.
this.state.movies && this.state.movies.length ? this.state.movies.map((movie) => {
return <Movie {...movie}/>
})
: null
}
<Search handleSendRequest={this.sendRequest}/>
</header>
</div>
);
}
}
export default App;
EDIT: Fixing res.body undefined.
import React from 'react';
import './App.css';
import unirest from 'unirest';
import Movie from './movie';
import Search from './search';
class App extends React.Component {
state = {
movies: []
}
sendRequest = (title) => {
const req = unirest("GET", "https://movie-database-imdb-alternative.p.rapidapi.com/");
req.query({
"page": "1",
"r": "json",
"s": title
});
req.headers({
'x-rapidapi-host': 'movie-database-imdb-alternative.p.rapidapi.com',
'x-rapidapi-key': 'my_api_key'
});
req.end((res) => {
if (res.error) throw new Error(res.error);
if(res && res.body && res.body.Search) {
const movies = res.body.Search;
this.setState({movies});
}
console.log(res.body);
});
}
render() {
return (
<div className="App">
<header className="App-header">
{
this.state.movies && this.state.movies.length ? this.state.movies.map((movie) => {
return <Movie {...movie}/>
})
: null
}
<Search handleSendRequest={this.sendRequest}/>
</header>
</div>
);
}
}
export default App;

Related

Redux - Unable to use dispatch to call action inside of axios response

I am new to react and redux, this is my first attempt at using a redux action to call an API with it returning a list of products which I can then add to the redux store for me to use in any component. So far the API call is working, and returns a list of products when I add a console.log in the then response, however when I use dispatch to call the next action which sets the type I receive the error "Unhandled Rejection (TypeError): dispatch is not a function".
Here is my Fetch.js file:
import axios from "axios";
import * as React from "react";
export function loadProducts() {
return dispatch => {
return axios.get(getApiHost() + 'rest/productComposite/loadProductsWithImages/' + getId() + '/ENV_ID').then((response) => {
dispatch(getProducts(response.data.productDtos));
})
}
}
export function getProducts(productDtos) {
return {
type: 'product',
productDtos: productDtos
}
}
function getId() {
return params().get('id');
}
function getEnv() {
let env = params().get('env');
if (!env) return 'prod';
return env;
}
function getApiHost() {
}
function params() {
return new URLSearchParams(window.location.search);
}
and my reducer.js file:
const initialState = {
loaded: 'false',
productDtos: []
}
const productReducer = (state = initialState, action) => {
switch (action.type) {
case 'product':
return {
...state,
loaded: 'true',
productDtos: action.productDtos
}
default:
return {
...state,
loaded: 'false',
productDtos: action.productDtos
};
}
}
export default productReducer;
and my index.js file:
(there is lots of messy code in this file which is why i am trying to convert the project into redux)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import * as serviceWorker from './serviceWorker';
import {createStore, compose, applyMiddleware } from 'redux';
import allReducers from './components/reducers'
import {Provider} from 'react-redux';
import thunk from "redux-thunk";
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
allReducers,
composeEnhancer(applyMiddleware(thunk)),
);
ReactDOM.render(
<React.StrictMode>
<Provider store = {store}>
<App/>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
and my app.js file:
import React from 'react';
import './App.css';
import Header from './Header';
import Footer from './Footer';
import PageHero from './PageHero';
import Products from './Products';
import ProductDetail from "./ProductDetail";
import Cart from "./Cart";
import ErrorBoundary from "./ErrorBoundary";
import PrivacyPolicy from "./PrivacyPolicy";
import LicenceAgreement from "./LicenceAgreement";
import {loadProducts} from "./Fetch";
import {connect} from "react-redux";
class App extends React.Component {
constructor(props) {
super(props);
this.cartProductsRef = React.createRef();
this.state = {
loadedShopConfig: false,
loadedLogo: false,
productView: false,
products: null,
logoUrl: null,
lAView: false,
pPView: false
};
this.onChange = this.onChange.bind(this)
this.changeBack = this.changeBack.bind(this)
this.addToCart = this.addToCart.bind(this)
this.lAViewChange = this.lAViewChange.bind(this)
this.pPViewChange = this.pPViewChange.bind(this)
}
params() {
return new URLSearchParams(window.location.search);
}
getId() {
return this.params().get('id');
}
getEnv() {
let env = this.params().get('env');
if (!env) return 'prod';
return env;
}
getApiHost() {
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({hasError: true});
// You can also log the error to an error reporting service
console.log('error', error);
console.log('info', info);
}
changeBack() {
this.setState({
productView: false,
lAView: false,
pPView: false
});
}
onChange(event) {
this.setState({productView: true});
this.setState({selectedProduct: event})
}
addToCart(product, quantity) {
console.log('cartProductsRef', this.cartProductsRef);
if (this.cartProductsRef.current) {
this.cartProductsRef.current.addToCart(product.entityInstanceId.id, quantity, product);
}
this.setState({})
}
lAViewChange() {
this.setState({lAView: true});
}
pPViewChange() {
this.setState({pPView: true});
}
loadShopDetails() {
this.setState({...this.state, isFetching: true});
fetch(this.getApiHost() + 'rest/shopComposite/' + this.getId() + '/ENV_ID')
.then((response) => response.json())
.then((responseJson) => {
console.log('Shop Details Function Results ', responseJson);
this.setState({
shopConfig: responseJson.shopConfig,
logoUrl: responseJson.logoUrl,
currencyCode: responseJson.currencyCode,
website: responseJson.website,
twitter: responseJson.twitter,
facebook: responseJson.facebook,
instagram: responseJson.instagram,
linkedIn: responseJson.linkedIn,
youTube: responseJson.youTube,
loadedShopConfig: true,
loadedLogo: true
});
})
this.setState({...this.state, isFetching: false});
}
componentDidMount() {
this.loadShopDetails();
this.props.dispatch(loadProducts());
}
render() {
let displayProduct;
const {lAView} = this.state;
const {pPView} = this.state;
const {productView} = this.state;
const {shopConfig} = this.state;
const {logoUrl} = this.state;
const {selectedProduct} = this.state;
if (productView && !lAView && !pPView) {
displayProduct = <ProductDetail
product={selectedProduct}
addToCart={this.addToCart}
/>;
} else if (!lAView && !pPView) {
displayProduct =
<Products
shopConfig={this.state.shopConfig}
productSelectedHandler={this.onChange}
/>;
}
return (
<div id="page">
<ErrorBoundary>
<p>{this.state.productView}</p>
<Header
logoUrl={this.state.logoUrl}
itemsInCart={this.state.itemsInCart}
changeBack={this.changeBack}
currencyCode={this.state.currencyCode}
/>
{!productView && !lAView && !pPView && this.state.loadedShopConfig ?
<PageHero shopConfig={this.state.shopConfig}/> : null}
{displayProduct}
<Cart id={this.getId()}
apiHost={this.getApiHost()}
ref={this.cartProductsRef}
currencyCode={this.state.currencyCode}
/>
{lAView ? <LicenceAgreement
shopConfig={this.state.shopConfig}
/> : null }
{pPView ? <PrivacyPolicy
shopConfig={this.state.shopConfig}
/> : null }
{this.state.loadedLogo ? <Footer
logoUrl={this.state.logoUrl}
lAChange={this.lAViewChange}
pPChange={this.pPViewChange}
twitter={this.state.twitter}
facebook={this.state.facebook}
instagram={this.state.instagram}
linkedIn={this.state.linkedIn}
youTube={this.state.youTube}
website={this.state.website}
/> : null}
</ErrorBoundary>
</div>
);
}
}
function mapDispatchToProps() {
return loadProducts()
}
export default connect(mapDispatchToProps)(App);
Thank you in advance for anyone who helps me, its probably a quick fix of something that I doing wrong, although I have read many articles and watched many videos and cannot find an immediate problem.
This is the way you dispatch an action in connected component. Notice that mapStateToProps is the first argument you pass into connect function, even if it returns an empty object:
import { connect } from 'react-redux'
import { loadProducts } from './path/to/actions'
class App extends React.Component {
componentDidMount() {
this.props.loadProducts();
}
render() { ... }
}
const mapStateToProps = () => ({});
const mapDispatchToProps = { loadProducts };
export default connect(mapStateToProps, mapDispatchToProps)(App);
Probably, you didn’t connect loadProducts

Fetching data from api in componentDidMount is returning null

I am trying to fetch data in componentDidMount lifecycle method of react but I am not getting it.
my method is:
componentDidMount() {
const { taskId } = this.props
getTask(taskId)
.then(data => {
console.log(data);
this.setState({task: data});
})
}
my api is:
export const getTask = (unique_id) => {
console.log(unique_id)
return fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/'+ unique_id).then(res => {
return res.json();
});
};
this is my whole component:
import React, { Component } from 'react'
import { getTask } from '../../modules/clients';
import ClientTaskShow from '../../components/tasks/ClientTaskShow'
class ClientTaskShowContainer extends Component {
constructor(props) {
super(props)
this.state = {
messageModalOpen: false,
selectedPartnerId: null,
task:{}
}
}
componentDidMount() {
console.log("hello")
const { taskId } = this.props
getTask(taskId)
.then(data => {
console.log(data);
this.setState({task: data});
})
}
render() {
const taskSelected = this.state.task;
console.log(taskSelected)
return (
<ClientTaskShow
task={taskSelected}
/>
)
}
}
export default ClientTaskShowContainer;
code from where calling clienttaskShowContainer:
import React from 'react'
import Head from 'next/head'
import Layout from '../../components/Layout'
import ClientTaskShowContainer from '../../containers/tasks/ClientTaskShowContainer'
import requireAuth from '../../lib/requireAuth'
const ClientTasksShow = ({ query }) => {
const { taskId } = query
return (
<Layout fluid fullHeight clientTaskHeader='true'>
<Head>
<title>Client Task Details | Punctual</title>
</Head>
<ClientTaskShowContainer taskId={taskId} />
</Layout>
)
}
ClientTasksShow.getInitialProps = async ({ query }) => ({
query
})
export default requireAuth(ClientTasksShow)
I think its not hitting the API even. Although it hit once I restart the server but not again. I am not able to replicate the problem.
At some sites I found we should use .then for API call others says we can't pass perimeter in API call in componentDidMount. What is the exact solution for this. Please help. Thanks in advance.
This code is working
//Calling component
import React from "react";
import CallComp from "./CallComp";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<CallComp taskId={"7693fbf81a33"} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// Child Component
import React, { Component } from "react";
import ClientTaskShow from "./ClientTaskShow";
class ClientTaskShowContainer extends Component {
constructor(props) {
super(props);
this.state = {
task: {}
};
}
componentDidMount() {
const { taskId } = this.props;
fetch(
`https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/${taskId}`
)
.then(response => response.json())
.then(data => this.setState({ task: data }))
.catch(error => console.log("the error is", error));
}
render() {
const taskSelected = this.state.task;
console.log("task selected is ", taskSelected);
return (
<div>
{Object.keys(taskSelected).length ? (
<ClientTaskShow task={taskSelected} />
) : (
<div>No data to show</div>
)}
</div>
);
}
}
export default ClientTaskShowContainer;
// Demo ClientTaskShow
import React from "react";
const ClientTaskShow = ({ task }) => {
return <h1>{task.unique_code}</h1>;
};
export default ClientTaskShow;
Actually its working
console.log(data) returns error message from api
You should return promise from function to know api request is resolved or not
try this:
export const getTask = (id) => {
return new Promise(function (resolve, reject) {
fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/' + id).then((res) => {
resolve(res.json())
})
});
}
And call like this:
componentDidMount() {
getTask(1).then((data)=>{
console.log(data);
});
}
You can replace params with your id
Hope this helps.

mapStateToProps is not defined

1.Can someone help me where i made a thing wrong?
2.the component i am mapping the state to its properties but i still get this
error"mapStateToProps is not defined"
this is the whole component below. the error reads "mapStateToProps not defined"
import React, {Component} from 'react';
import Icon from 'react-native-vector-icons/EvilIcons';
import { loadInitialPosts} from './actions';
import {connect } from 'react-redux';
import _ from 'lodash';
import {View, StyleSheet,FlatList} from 'react-native';
import PostItem from './PostItem';
import PostDetail from './PostDetail';
class PostsList extends Component {
componentWillMount() {
this.props.loadInitialPosts();
}
renderItem({item}){
return <PostItem posts = { item } />;
}
renderInitialView(){
if(this.props.postDetailView === true){
return(
<PostDetail />
);
}
else{
return(
<FlatList
data={this.props.posts}
renderItem={this.renderItem} />
)}
}
render(){
return(
<View style={styles.list}>
{this.renderInitialView()}
</View>
);
}
}
const mapStateToProps = state => {
const posts = _.map(state.posts, (val, id) =>
{
return { ...val, id};
});
return{
posts: posts,
postDetailView: state.postDetailView,
};
}
export default connect(mapStateToProps, { loadInitialPosts })(PostsList)
1.This is the action that dispatches the data
export const loadInitialPosts = () => {
return function(dispatch){
return axios.get(apiHost
+"/api/get_posts?
count=20")
.then((response) => {
dispatch({ type:
'INITIAL_POSTS_FETCH', payload:
response.data.posts});
}).catch((err) => {
console.log(err);
});
};
};
mapStateToProps sits outside of the class before export default connect(mapStateToProps)(SomeClass)
class SomeClass extends React.Component {
...
}
const mapStateToProps = state => {
const posts = _.map(state.posts, (val, id) => {
return { ...val,
id
};
});
return {
posts: posts,
postDetailView: state.postDetailView,
};
}
To eliminate the possibility of mapStateToProps being undefined, consider defining the mapStateToProps directly in the call to connect() like this:
class PostsList extends React.Component {
componentWillMount() {
this.props.loadInitialPosts();
}
renderItem({item}){
return <PostItem posts = { item } />;
}
renderInitialView(){
if(this.props.postDetailView === true){
return <PostDetail />;
}
else{
return <FlatList
data={this.props.posts}
renderItem={this.renderItem} />
}
}
render(){
return(<View style={styles.list}> {this.renderInitialView()} </View>);
}
}
/*
Avoid declaration of mapStateToProps object by defining this object
directly in the call to connect()
*/
export default connect((state => {
return {
posts : state.posts.map((val, id) => ({ ...val, id })),
postDetailView: state.postDetailView,
}
}), { loadInitialPosts })(PostsList)

ReactJS - how to update data for an attribute in props?

I have a list of posts and for every post, there's is a button that will display a modal window with a confirmation if the user really wants to delete the respective post.
When the user confirms, data are send to backend, there's delete the respective post and back to ReactJS is returned a set of all posts. But when try to update the list of posts on the front-end, I get this error:
Posts.jsx:61 Uncaught (in promise) TypeError: _this2.props.posts is not a function
This error is raised on this line:
this.props.posts(res.data);
Home.jsx
import React from "react";
import Posts from './Posts';
import NewPost from './NewPost';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
loading: true
};
}
componentDidMount() {
axios.get('/posts')
.then(response => {
console.log('---');
console.log(response.data);
console.log('---');
this.setState({ posts: response.data, loading: false });
});
}
render() {
return (
<div>
<Posts posts={this.state.posts} loading={this.state.loading} />
</div>
)
}
}
export default Home
Posts.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Collapse} from 'react-collapse';
import classNames from "classnames";
import Dialog from 'react-bootstrap-dialog';
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: null,
removePostBtn: 'Remove'
}
}
onClick(post_id) {
this.dialog.show({
title: 'Remove Post - #'+post_id,
body: 'Do you really want to remove this post?',
actions: [
Dialog.CancelAction(),
Dialog.DefaultAction(
this.state.removePostBtn,
() => {
this.setState({ removePostBtn: 'Removing...' }, () => {
axios.get('/remove_post/'+post_id, { post_id: post_id })
.then(res => {
this.props.posts(res.data); // here's the error
})
})
},
'btn-danger'
)
],
})
}
render () {
let content;
const { activeIndex } = this.state;
const Button = require('react-bootstrap').Button;
if (this.props.loading) {
content = 'Loading...';
} else {
content = this.props.posts.map((post, index) => {
return(
<li key={index}>
<div>
<span>{post.id}</span>
<span>{post.message}</span>
<Button onClick={() => this.onClick(post.id)}>Show alert</Button>
<Dialog ref={(el) => { this.dialog = el }} />
</div>
</li>
)
});
}
return (
<div>
<h1>Posts!</h1>
<div className="row">
<div className="col-md-6">
<ul>
{content}
</ul>
</div>
</div>
</div>
);
}
}
export default Posts
How do I properly update the props with posts?
You can't directly update any props. You need to create an update handler in the parent component that will update this.state.posts:
import React from "react";
import Posts from './Posts';
import NewPost from './NewPost';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
loading: true
};
}
componentDidMount() {
this.getPosts();
}
getPosts = () => {
axios.get('/posts')
.then(response => {
console.log('---');
console.log(response.data);
console.log('---');
this.setState({ posts: response.data, loading: false });
});
}
updatePosts = posts => {
this.setState({ posts });
}
render() {
return (
<div>
<Posts posts={this.state.posts} loading={this.state.loading} getPosts={this.getPosts} updatePosts={this.updatePosts} />
</div>
)
}
}
export default Home
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Collapse} from 'react-collapse';
import classNames from "classnames";
import Dialog from 'react-bootstrap-dialog';
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: null,
removePostBtn: 'Remove'
}
}
onClick(post_id) {
this.dialog.show({
title: 'Remove Post - #'+post_id,
body: 'Do you really want to remove this post?',
actions: [
Dialog.CancelAction(),
Dialog.DefaultAction(
this.state.removePostBtn,
() => {
this.setState({ removePostBtn: 'Removing...' }, () => {
axios.get('/remove_post/'+post_id, { post_id: post_id })
.then(res => {
//this.props.posts(res.data); // here's the error
// Call parent function to re-retch posts
this.props.getPosts();
// Or direclty pass data to update the parent state
this.props.updatePosts(res.data);
})
})
},
'btn-danger'
)
],
})
}
render () {
let content;
const { activeIndex } = this.state;
const Button = require('react-bootstrap').Button;
if (this.props.loading) {
content = 'Loading...';
} else {
content = this.props.posts.map((post, index) => {
return(
<li key={index}>
<div>
<span>{post.id}</span>
<span>{post.message}</span>
<Button onClick={() => this.onClick(post.id)}>Show alert</Button>
<Dialog ref={(el) => { this.dialog = el }} />
</div>
</li>
)
});
}
return (
<div>
<h1>Posts!</h1>
<div className="row">
<div className="col-md-6">
<ul>
{content}
</ul>
</div>
</div>
</div>
);
}
}
export default Posts

ReactJS - setState Axios POST response

I'm trying to set a state for my Axios POST response but the array where I map the data is still empty. The data fetching is working good, but I just need to move all the data with the 'subject' keywords to my Todos array and print them out.
Here is my code so far;
App.js
import React, { Component } from 'react';
import axios from 'axios';
import Todos from "./Components/Todos"
class App extends Component {
constructor(){
super();
this.state = {
todos:[]
}
}
// AXIOS request
getTodos(){
var postData = {
"startDate": "startDate",
"endDate": "endDate",
"studentGroup": ["ID"]
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Authorization': "Basic " + btoa("username" + ":" + "password")
}
};
axios.post('url', postData, axiosConfig)
.then((data) => {
console.log(data);
this.setState({todos: data.reservations ? data.reservations : []}, function(){
console.log(this.state);
})
})
.catch((err) => {
console.log("Error: ", err);
})
}
componentWillMount(){
this.getTodos();
}
componentDidMount(){
this.getTodos();
}
render() {
return (
<div className="App">
<Todos todos={this.state.todos}/>
</div>
);
}
}
export default App;
Todos.js
import React, { Component } from 'react';
import TodoItem from './TodoItem';
class Todos extends Component {
render() {
let todoItems;
if(this.props.todos){
todoItems = this.props.todos.map(todo => {
return (
<TodoItem key={todo.subject} todo={todo} />
);
});
}
return (
<div className="Todos">
<h3>Results:</h3>
{todoItems}
</div>
);
}
}
export default Todos;
TodoItem.js
import React, { Component } from 'react';
class TodoItem extends Component {
render() {
return (
<li className="Todo">
<strong>{this.props.todo.subject}</strong>
</li>
);
}
}
export default TodoItem;
Snippet from console before setState:
Should I use some other function instead of an arrow function?
if you don't get this.setState is undefined error then it's a bit strange. Could you fix/copy the code below and verify if that helps:
import React, { Component } from 'react';
import axios from 'axios';
import Todos from "./Components/Todos"
class App extends Component {
constructor(props){
super(props); // pass props to "father" constructor
this.state = {
todos:[]
}
this.getTodos = this.getTodos.bind(this);
}
// AXIOS request
getTodos(){
var postData = {
"startDate": "startDate",
"endDate": "endDate",
"studentGroup": ["ID"]
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Authorization': "Basic " + btoa("username" + ":" + "password")
}
};
axios.post('url', postData, axiosConfig)
.then((response) => {
if(response.data.reservations) {
this.setState({todos: response.data.reservations})
}
})
.catch((err) => {
console.log("Error: ", err);
})
}
componentDidMount(){
this.getTodos();
}
render() {
console.log(this.state.todos);
return (
<div className="App">
<Todos todos={this.state.todos}/>
</div>
);
}
}
export default App;
Now observe if console.log(this.state.todos); is called after the request is finished. If so, verify it's an empty array.
Create self reference in function
getTodos(){
var self = this; // create a this reference
var postData = { .. };
let axiosConfig = {... };
axios.post(..)
.then((data) => {
self.setState('your updated state')
})
.catch((err) => {});
}
I was having hard time with the "this" undefined. I solved it like this (calling function should be arrow function):
handleGenerateCharge =(event) => {
const header = new Headers();
header.append('Access-Control-Allow-Origin', '*');
var charge = {
name: "ABC",
createDate: Moment(Date.now()).format()
}
axios.post("http://url", charge, header)
.then((res) => {
if (res.status === 200) {
this.update();
}
}).catch((error) => {
this.setState({ errorMessage: error });
})
event.preventDefault();
}

Categories

Resources