I am struggling with utilizing the data that has been fetched in JavaScript. Despite successfully retrieving the data, I am facing difficulties in effectively using it in

I am facing an issue where I am unable to utilize the data after fetching it from a local JSON file. Below are the screenshots showcasing the problem: Here is the data displayed in the console: Here is the code snippet:


fetch('api_link.json')
.then((res) => res.json())
.then((data) => {
    console.log('data:', data);
  })

export const project_info = () => async (dispatch) => {
  try {
    dispatch({ type: PROJECT_INFO_REQUEST });

    var { data } = await axios.get('HERE I WANT TO PUT THE DATA FROM THE JSON FILE');

    dispatch({
      type: PROJECT_INFO_SUCCESS,
      payload: data,
    });
Additionally, here is another screenshot for clarification. Can anyone provide assistance with this issue? #note I am a Python backend developer :) This is my first time working with React JS.

Answer №1

Scope of function arguments is limited to the function itself and cannot be accessed from outside the function.

It's worth noting that there is no guarantee that the network request will be resolved before calling the project_info function.

To ensure that the promise returned from fetch is accessible within the project_info function, save it in a variable.

const api_data = fetch('api_link.json')
    .then((res) => res.json())

export const project_info = () => async (dispatch) => {
            try {
                dispatch({
                    type: PROJECT_INFO_REQUEST
                });

                const url = await api_data;

                var {
                    data
                } = await axios.get(url);

                dispatch({
                    type: PROJECT_INFO_SUCCESS,
                    payload: data,
                });

It's important to note that axios and fetch serve the same purpose as APIs. It's better not to mix them.

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

The jstree does not seem to be generating the tree structure as expected based on

I am utilizing the jstree plugin to construct a hierarchical tree view of locations, rooms, and assets for a company within a PHP application that I am developing. The main intention behind this tree is to enable users to select an asset while going throu ...

Convert a Ruby string into a JSON formatted string

When working with the json gem, I ran into an issue where directly encoding strings to their JSON representation was not possible. To solve this problem, I tried adapting some PHP code: $text = json_encode($string); into Ruby like this: text = string.in ...

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

Check if a specific string is present in an array using JavaScript

When working with SQL, we can easily check if a string is in a list using the following syntax: Column IN ('a', 'b', 'c') But how can we achieve this in JavaScript without it being so cumbersome? if (expression1 || expressi ...

Create an XML file with recurring elements based on JSON data

Currently, I am utilizing the xmlBuilder library within Nodejs to generate XML from a prepared JSON object. My approach involves crafting the JSON structure first and then transforming it into XML using Javascript as the coding language. The specific XML ...

Scale up the font size for all text on the website uniformly

Recently, I decided to switch a website's font to a non-web typeface. However, I quickly realized that the font was extremely thin and difficult to read. I attempted a simple CSS fix using * { font-size:125% }, but unfortunately, it did not have the d ...

Pressing "Enter" initiates the submission of the form

My webpage contains a stylish GIF displayed as a button within a div. The script inside the div triggers a click event when the ENTER key is pressed, using $(this).click(). This click action has its own functionality. Everything functions smoothly in Fire ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

Steps for configuring mode as 'open' when generating a shadow element with vue-custom-element

Here is the method I used to generate a shadow component Vue.customElement('my-element', MyElement, { shadow: true, shadowCss: mystyles, }); ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

what strategies can be implemented to prioritize addressing validation errors in return forms

I'm currently working on a web application in asp.net mvc-5, and I have a contact form displayed in the middle of the Contact Us view. Here's the code snippet: <div class="col-sm-8 col-sm-push-4"> <h2>Contact Us1 ...

Create a project in asp.net core API that allows for CRUD operations using JSON and static data

What is the process for performing CRUD operations on a locally stored JSON file? Specifically, with an example where there are fields like id, name, and roll number. I am looking to implement GET, POST, PUT, and DELETE functionalities using ASP.NET Core ...

I can't understand why my server is displaying an error on the browser stating "This site can't be reached ERR_UNSAFE_PORT" while it is functioning flawlessly on the terminal

I have created an index.html file, along with index.js and server.js. In the server.js file, I have included the following code: const express = require("express"); const path = require("path" ); const app = express(); app.use(" ...

Struggling with an issue in React and Bootstrap4 while developing an application with create-react-app

In my experience with Windows 10, I encountered two scenarios where I faced problems. The first scenario involved creating applications using the create-react-app command and installing it with npm i -g [email protected]. Scenario 1 I stopped the React s ...

issue with react prop causing my function to function in one scenario but fail in another

I'm a bit confused with these two functions. Although they seem identical to me, only the first one is able to generate images from this.state.images. Any guidance on this seemingly small mistake would be much appreciated. The following code snippet ...

Strategies for dynamically altering Vue component props using JavaScript

for instance: <body> <div id="app"> <ro-weview id="wv" src="http://google.com"></ro-weview> </div> <script> (function () { Vue.component("ro-webview", { props: ["src"], template: ` <input type="t ...

Select2 is throwing an error that says "Unidentified problem with property 'results'."

Currently, I am working on populating a searchable Select2 form-control with search results extracted from Active Directory. Let's take a look at the select2 function implementation: $("#networkUserSelect").select2({ ajax: { url: ' ...

Why is it necessary to type in localhost in the address bar when using node.js and socket.io instead of simply opening the client.html file directly?

I am intrigued by this topic. My suspicion is that it may be related to the temporary file created by socket.io, but I'm struggling to fully understand it... ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

Issue with ServiceStack GET action resulting in a null object being returned

I've encountered an issue with a ServiceStack service where the JSON object is no longer being passed in when calling the GET action, even though I recently made some changes to fix the POST action. It's baffling me and I can't seem to figur ...