React native and redux: Updating state with setState is not possible during an ongoing state transition

Currently in the process of developing an app utilizing React Native and redux, alongside Express js for handling Ajax requests.

Encountering an issue where the data from my Ajax request fails to load, accompanied by the following warning:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

Puzzled about what might be causing this error?

index.ios.js

Developed using React Native to create an android application that showcases various functionalities neatly put together.

store.js

Incorporated different reducers and middleware into the store configuration for optimized state management and data flow.

Displaying the view file:

Utilized React components to build an interactive user interface that communicates with Redux for smooth data handling.

Action file:

Defined actions and async functions for fetching data through Ajax calls, ensuring seamless integration between front-end and back-end operations.

Reducer setup:

Implemented reducers to handle dispatched actions and manage state updates based on received data from fetch requests.

Answer №1

Consider trying out this code snippet. It hasn't been tested extensively, but it captures the main idea:

import React, {Component} from 'react'
import {
  View,
  ListView,
  ScrollView,
  StyleSheet,
  Image,
  TouchableHighlight
} from 'react-native'

import { connect } from 'react-redux'
import Listings from './listings'
import BetView from './bet-view'
import { getListings } from './actions/listings'

const getDataSource = (listings) =>
  (new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 != r2
  })).cloneWithRows(listings)

class _ListingsView extends Component {


  componentWillMount() {
    this.props.onLoad();
  }

  render() {
    return(
      <ScrollView>
        <ListView
          dataSource={this.props.dataSource}
          renderRow={(row) =>
            <Listings
              teamOne={row.game[0]}
              teamTwo={row.game[1]}
              date={row.date}
              onPress={() => this.props.onPress(this.props.navigator, row.name)}
            />
          }
        />
      </ScrollView>
    )
  }
}

const ListingsView = connect(
  (state) => {
    return {
      dataSource: getDataSource(state.listings.items || []),
      loading: state.listings.loading
    }
  },
  (dispatch) => {
    return {
      onPress: (navigator, name) =>
        navigator.push({
          title: 'test',
          component: BetView,
          passProps: {
            category: name
          }
        }),
      onLoad: () => dispatch(getListings())
    }
  }
)(_ListingsView)

export default ListingsView

For more guidance, you may want to refer to the react-native documentation on ListViews: https://facebook.github.io/react-native/docs/listview.html

Alternatively, here's how I handle ListViews in my current application: https://github.com/kamiranoff/mythology/blob/master/src/components/HeroesList/HeroesList.js (In this example, there's some advanced pre-render data fetching involved, so the datasource state update is managed in componentWillReceiveProps )

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

Trouble triggering hidden radio button in Angular 9 when clicked

I have implemented radio buttons within a div with the following CSS styles (to enable selection by clicking on the div): .plans-list { display: flex; justify-content: center; margin: 2rem 0; .plan { display: flex; margin: 0 0.5rem; p ...

I am curious about the inner workings of the `createApplication()` function in the ExpressJS source code. Can you shed some light on

My goal is to deeply comprehend the inner workings of the Express library, step by step. From what I gather, when we import and invoke the 'express()' function in our codebase, the execution flow navigates to the ExpressJS library and searches fo ...

Transmit information from JavaScript to a servlet and receive a response in return

I'm new to using ajax and JavaScript. Currently, I have a simple jsp page containing HTML and an accompanying JavaScript file with all my functions defined. One of these functions sends JSON data to a servlet and now I need assistance in receiving th ...

What are some ways to implement dangerouslySetInnerHTML in conjunction with read-more-react from npm?

Is there a way to include dangerouslySetInnerHTML in a text field without receiving an error? <ReadMoreReact text={yourTextHere} min={minimumLength} ideal={idealLength} max={maxLength} readMoreText={read ...

Is it possible to transform an array of objects into a new array of objects?

After searching for a similar question, I realized none of them really addressed my issue... EDIT: My main goal is to create a reusable dropdown component where I can pass items as props directly. These items need to be objects with both a key (for the fi ...

Divergent functionality of regular expressions in Internet Explorer and Chrome when handling white spaces

Here is a function that validates input by checking for numbers and no spaces in between: checkInputValidity: function() { var isValid = true; var idNumber = this.getView().byId("iDNumber"); var regex = /^[0-9]+$/; if (idN ...

Change the background color of a particular row in a table using Vue.js to be red

I am having an issue with a regular table - when I click on a specific row, I want only that row to turn red. Below is the code snippet that I have attempted: <tr role="row" v-for="(proxy, key) in this.ProxiesList" @click.prevent=&q ...

Issues arise when trying to render a component in React after importing the react-bootstrap library

After running npm init and installing react, react-dom, bootstrap, and react-bootstrap packages, I encountered an issue while trying to import components from the react-bootstrap library. The code import Button from 'react-bootstrap/Button'; resu ...

The React Fabric TextField feature switches to a read-only mode once the value property is included

I've been grappling with how to manage value changes in React Fabric TextFields. Each time I set the value property, the component goes into read-only mode. When utilizing the defaultValue property, everything functions correctly, but I require this i ...

Adjust the Appearance of Highcharts Legend Post-Rendering

After a Highchart is rendered, is it possible to modify the display settings without redrawing the chart? For instance, I would like to relocate the legend box from the right to the bottom upon screen resize, as illustrated in this image: --Example Pictur ...

"How to set the header in AngularJS when opening a new window with a GET request URL

Can anyone provide guidance on setting headers and opening a URL (https://www.example.com) in a new window without including sensitive authentication information in the URL parameters? I am working with AngularJS for this task. I have searched through exi ...

Exploring the use of Rails and jQuery to automatically update data through the use of setTimeout and ajax calls

There's a specific page accessible in the browser at "/calendar" that directs to "calendar#index". Utilizing a javascript setTimeout function, I'm attempting to re-fetch and update data on my page using $.get ajax method. $.get("<%= calendar ...

Tips for linking my TypeScript document to the server

Recently diving into the world of Angular 2 and seeking to grasp its intricacies. Currently utilizing Visual Studio Code. How can I have the server monitor changes in the TypeScript file? Do I need a compiler to convert it to JavaScript for this purpose? ...

Synchronization issue between Material UI SelectField component and state is observed in React/Redux setup

My issue involves the LayoutSelector component which contains a drop-down form that updates the state.plate.layout. The state is passed as a prop to the component. On my local machine, the selected menu item accurately reflects the state changes - when a n ...

Setting an Element's attribute is only visible in the console

Just dipping my toes into the world of Web Development. While playing around with some JavaScript within HTML, I decided to try updating the content of an element. Upon running the code below, "Updated Content" appears in the console as intended. However, ...

Tips for increasing the height of a popover when clicked

When a user focuses on the password input, a popover displays information. At the bottom of the popover, there is a link. How can I make the popover expand when the user clicks on this link? I have tried adding an !important class for the height value, us ...

Importing a JavaScript file into another JavaScript file

var FS = require('fs'); var Path = require('path'); var Jsonfile = require('jsonfile'); var search = function () {}; search.prototype.projectContainerDirPath = null; /* * interface */ search.prototype.setPaths = function ...

How to include images in a PDF using jspdf without encountering issues with Adobe Reader?

For a project I'm working on, I've integrated jspdf to convert some charts into a PDF. The framework I'm using is angularjs 1.5.6, and the charts are created with chart.js. The HTML snippet for the charts looks like this: <div name="char ...