Having trouble retrieving state data within a functional component in React Native

I've been facing a challenge while developing an app in React Native. The issue lies in understanding how to manage state in functional components.

After successfully fetching and storing an array of activities in the component's state, I encountered difficulties when trying to make additional fetches related to these activities. Specifically, I needed to access each activity's ID from the state, but all I saw in the console log was an empty array.

Despite confirming that everything was executing in the correct order by analyzing the timestamps, I couldn't figure out why I couldn't access the state in this particular scenario. In other parts of the code, accessing the state and retrieving the full array of activities worked perfectly fine. So, what could be causing the issue here?

Below is the snippet of code:

  const [activities, setActivities] = useState([]);

  async function getActivites(cred){
    const zeroLevel = Date.now();
    fetch(`https://www.strava.com/api/v3/athlete/activities?access_token=${cred.access_token}`)
        .then((res) => res.json())
        .then((data) => {
          for (const element of data) {
            setActivities(oldActivities => [... oldActivities, element])
            console.log(Date.now() - zeroLevel)
          }
          console.log('for-loop finished', Date.now() - zeroLevel)
        })
        .then(() => console.log(Date.now() - zeroLevel))
        .then(() => console.log(activities))
  }

I attempted to store the array in another object as a workaround, but I am convinced there must be a simpler solution.

Answer №1

In the case where data is an array, there is no need to iterate through it. Instead, you can directly assign the activities with the data without looping:

.then((data) => {
  setActivities(data)
  console.log('fetch finished', Date.now() - zeroLevel)
  return data 
})
.then((data) => {
  data.map(activity => // perform fetch on each activity)
}

Alternatively, if you prefer to chain the fetch based on the state, you can manually monitor the changes like this:

.then((data) => {
  setActivities(data)
  console.log('fetch finished', Date.now() - zeroLevel)
})

useEffect(() => {
 activities.map(activity =>// perform fetch on each activity)
},[activities])

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

What is the best way to integrate the react-simple-captcha canvas element within an MUI Dialog component?

I've recently encountered an issue while trying to integrate react-simple-captcha into the submission form of my React app. The form is nested inside an MUI Dialog component on a specific page. Strangely, when the captcha element is not within a Dialo ...

Comparing defaultProps with the logical OR operator

Being relatively new to react, I’ve adopted a method of defining default values which looks like this: class TextInput extends Component { render() { return ( <input type="text" name={ this.pr ...

The MaterialUI TextField isn't behaving as expected when attempting to change the background color

Currently, I am facing a challenge with setting the background color for my `TextField` components within the app I am developing. Despite adding custom RGB values using `style={{background: "rgb(232, 241, 250)"}}`, the component continues to dis ...

What are the steps for retrieving data on the server side by utilizing a token stored in localStorage?

Currently, I am diving into the official documentation for Next.js and utilizing the App router. On the data fetching patterns page, it explicitly states: Whenever possible, we recommend fetching data on the server To adhere to this recommendation, I cr ...

React component will be visible regardless of the URL provided

Currently, I am working through a tutorial using the react-router-dom React library. One issue I am facing is that my navigation header continues to display no matter what URL I enter after localhost:3000. For example, even if I type localhost:3000/dflkjf ...

Can we enhance the efficiency of this equation?

The formula provided organizes the elements in the container based on mouse movement. The issue stemmed from the image size and the different calculations performed when approaching along the x and y axes from various directions. const zoomEffect = (even ...

Unable to utilize the MUI 'ContentCopy' icon at the moment

I'm attempting to incorporate the 'ContentCopy' icon from MUI. https://mui.com/components/material-icons/ recommends using this import statement: import ContentCopyIcon from '@mui/icons-material/ContentCopy'; Despite my efforts, ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

The backend API does not receive the correct value from the checkbox

I'm having an issue with my registration page in ReactJS. There is a checkbox field called isadult. After clicking on the Register button and saving the data to a MongoDB database, the value of isadult shows up as [Object object] instead of True or Fa ...

Dynamically change the fill color of an SVG using styled-components

I've been attempting to target the fill property of my SVG using CSS in styled-components without any luck. Here is my SVG: <svg width="65" height="19" viewBox="0 0 65 19" fill="none" xmlns="http://www. ...

In order to access the latest version on Google Cloud (App Engine), I must first clear my cookies

Recently, I started using Google Cloud to host my React application. The version of React that I am using is "16.8.3" (although I don't think it's relevant to my issue). The problem arises when I make some updates to the application by running & ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

Error: The value for 'prepareStyles' property is undefined and cannot be read

Can anyone provide some guidance on this code snippet? I am struggling to understand the error message I am receiving. import React, {PropTypes} from 'react'; import TransactionListRow from './TransactionListRow'; import {Table, TableB ...

React - Uncaught Error: e.preventDefault is not a function due to Type Error

Encountering an issue with Axios post and react-hook-form: Unhandled Rejection (TypeError): e.preventDefault is not a function The error arises after adding onSubmit={handleSubmit(handleSubmitAxios)} to my <form>. Seeking to utilize react-hook-form ...

I am attempting to create basic animations using css, but I'm having some trouble

Currently, I am attempting to add animation to a css div without including the top property in the original div style. I omitted it because I wanted to delay the animation, so I placed it within the @keyframes property. However, the element disappears afte ...

The issue with ReactJS Material-UI's theme.mixins.toolbar offset not adjusting properly when the <toolbar variant="dense"/> is applied

Looking for a solution to adjust the offset of content behind the Material-UI AppBar in a clean way. I initially thought that theme.mixins.toolbar would automatically adapt, but that doesn't seem to be the case. (Even using the theme density prop as ...

What is the method for sending an axios post request using the application/x-www-form-urlencoded content type?

How can I successfully send an axios post request using application/x-www-form-urlencoded? I am trying to include a refresh token in the request, but currently an empty object is being sent. However, I have verified that the token exists when checking "us ...

website pages loading faster than images can load

I run a website dedicated to music instruments, and I have implemented a carousel feature that displays images at intervals. However, I encountered an issue when converting my high-resolution images to base64 for storage in the database ...

The SunEditor onChange event does not reflect updated state information

software version next: 12.0.7 suneditor: 2.41.3 suneditor-react: 3.3.1 const SunEditor = dynamic(() => import("suneditor-react"), { ssr: false, }); import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS Fi ...

Transferring information from a React Native app to a Node.js server using Express

Looking for advice on transferring data between React Native and Node.js (Express)? I'm currently developing an app using React Native and Node.js with Express, but struggling to establish communication for data exchange. Any tips would be greatly ap ...