Pass the JSON object to a separate .js file in react-native without using class declarations

I am currently working on a mobile app that utilizes the fetch API to make GET calls. I've encountered an issue where I'm trying to export a JSON object fetched from the server using the fetch method to another .js file in order to use it as an array. However, when I import my function into another.js, it doesn't return anything. I have tested the fetch method using console and it works as expected, but for some reason I can't process the data in the another.js file. I tried looking for solutions and came across this post Helpful, but it didn't solve my problem.

The code below shows the implementation of the fetch part and how it is exported (Products.js)

import React, { PureComponent,Component } from "react";
 import { connect } from "react-redux";
 import { View } from "react-native";
 import { productsDataSelector } from "../../Products/ProductsSelectors";
 import ProductsList from "../../ProductsList/ProductsList";
 import Product from "../../Product/Product";
 import { NavigationActions, StackActions } from "react-navigation";
 import AnotherComponent from "../../Products/ProductsReducer";
 class Products extends PureComponent  {

  render() {
const { navigation } = this.props;

const { productsData } = this.props;
return (

  <View>
    <ProductsList list={productsData} isSortable>
      {product => <Product product={product} />}
    </ProductsList>
  </View>
     );
  }
}

 const mapStateToProps = state => ({
   productsData: productsDataSelector(state)
 });
  export  const  getMoviesFromApiAsync = () =>
 fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())


export default connect(
  mapStateToProps,
  null
     ) (Products);

The code below is for another.js where the fetch function is imported and processes the returning JSON object without implementing a class declaration.

import React, { Component } from "react";
 import {getMoviesFromApiAsyncc} from "../screens/Products/Products";


 const fakeData = [];



 export const someFunc = () => {

 fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
   .then((response) => response.json())
  .then((responseJson) =>     console.log("responsee:"+JSON.stringify(responseJson)))
  .then((responseJson) =>  {fakeData:JSON.stringify(responseJson)})

  .catch((error) => {
    console.error(error);
      });

};
someFunc();

const initialState = {
  data:this.fakeData

};

export default (state = initialState,action) => {
  return state;
};

Any suggestions or recommendations would be greatly appreciated. Thank you!

Answer №1

It seems like there is a missing call to someFunc in your code. Additionally, make sure to wrap the object returned from someFunc in braces so that it is not mistaken for the function's body.

export const someFunc = () => {
  getMoviesFromApiAsync().then(response => {
    fakeData = JSON.stringify(response)
  })
};
someFunc();

I recommend moving getMoviesFromApiAsync to a separate file and calling it from your component to retrieve the list of movies.

api.js

export const getMoviesFromApiAsync = () =>
  fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
    .then((response) => response.json());

product.js

import React, { PureComponent,Component } from "react";
import { connect } from "react-redux";
import { View } from "react-native";
import { productsDataSelector } from      "../../Products/ProductsSelectors";
import ProductsList from "../../ProductsList/ProductsList";
import Product from "../../Product/Product";
import { NavigationActions, StackActions } from "react-navigation";
import AnotherComponent from "../../Products/ProductsReducer";
// import getMoviesFromApiAsync
import { getMoviesFromApiAsync } from 'PATH_TO_API.JS'


class Products extends Component {

  async componentDidMount(){
    const list = await getMoviesFromApiAsync();
    console.log(list);
  }

  render() {
    const { navigation } = this.props;

    const { productsData } = this.props;
    return (


      <View>
        <ProductsList list={productsData} isSortable>
          {product => <Product product={product} />}
        </ProductsList>
      </View>
    );
  }
}

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

Accessing a factory's functions within itself in Angular

I'm really trying to understand how all of this operates. It seems like it should be working as intended. I have an Auth factory that, when the jwt token expires, calls its 'delegate' method which obtains a new token using the refresh token. ...

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...

"Trouble displaying specific events based on their IDs retrieved from the MySQL database

Each button in my list is associated with a specific person. Upon clicking a button, it directs to calendar.php?id=5 (where 5 is the personal id). I want the calendar to display the vacations scheduled for that particular id from the MySQL database. even ...

Learn the steps to successfully rotate the custom icon in Material-Ui select without impacting its functionality and making sure it remains clickable

I've been trying to incorporate my own icon for the material UI select component. I successfully replaced the default icon using the "IconComponent" attribute in MU select. However, I'm facing issues with the new icon not rotating when the menu ...

Unique text: "Enhancing User Interaction: Using a custom directive to dynamically evaluate

Introduction: A simple demonstration of HTML structure: <td ng-repeat="col in cols"> <div ng-bind-html="col.safeHTML"></div> </td> JavaScript controller code snippet: $scope.cols = [ { field : 'logo&apos ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

The pop-up menu appears in a location different from where the anchor element is positioned

Having an issue with the menu placement when clicking on an Avatar. The menu is appearing in the wrong position: https://i.sstatic.net/955eJ.png The avatar button "OB" on the right side is where the issue occurs. No console errors present and inspecting ...

The URL for the Javascript chunk includes colons at https://example.com/js/chunk-vendors.b3792e11.js:18:16400

I recently completed a Vue application and used npm run build to generate the files. Upon uploading the dist folder to my Apache server, I encountered an issue where Apache was unable to locate the file when trying to access a specific part of the app (:18 ...

Send a POST request with an NSDictionary set in the HTTPBody

I need to make a web service call using the POST method. I have to send a dictionary along with a URL to my web service. Below are the parameters required for my web service: ConversationMessage { authorUserId (string, optional), subject (st ...

Having trouble with redundant code while updating state in ReactJS - React JS

Currently, I am working on a prayer times web app using reactJS (nextjs). To achieve this, I first fetch the geolocation coordinates and then retrieve the city and country name based on these coordinates. Following that, I obtain the prayer times for the s ...

"Encountering issue with componentDidMount() not functioning as expected, despite debugger being

Hello everyone! This is my first time sharing something here, so I'm eager to hear your feedback on both how I've posted and the content itself. I've only been programming for 8 weeks now, so I'm sure there are plenty of mistakes in wha ...

Babel continues to encounter issues with async/await syntax, even with all the necessary presets and plugins installed

I am encountering a compiler error while attempting to compile an async/await function using Babel. Below is the function in question: async function login(username, password) { try { const response = await request .post("/api/login") . ...

Utilizing _.partial on a single-argument function

Currently, I am in the process of refactoring code within a react.js application. There is an element that utilizes Underscore.js _.partial on a function that already has one argument. Is there any real benefit to doing this? I can see how it works based ...

Tips on completing landing page animations and displaying the main page of a website by utilizing React JavaScript

https://i.stack.imgur.com/M4VgY.pngIs there a way to stop the landing page animation after 2-3 seconds and show the main page instead? Can I achieve this by using setTimeOut function in JavaScript? [ export default Loader; ...

Encountering an issue with Material-UI and Next.js: "TypeError: theme.spacing is not a function

Encountering an issue after modifying _app.js to dynamically generate a material UI theme. I've been following the implementation example provided by the material-ui team at: https://github.com/mui-org/material-ui/tree/master/examples/nextjs. To summ ...

How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet ...

Retrieve a JSON file with Hebrew data from a server and then interpret it using Node.js

I have a JSON file with dynamic content stored on a remote server acting as an API. The file also includes Hebrew text in its values. How can I retrieve the response and convert it into a JSON object? Here is the code snippet I have put together using Re ...

Looking for a different option than JSON.stringify()? Check out JSON2.js for

Currently, I am attempting to initiate a WCF call to a function that requires one String parameter. To pass these parameters from jQuery, I utilize JSON.stringify(parameters), which consists of a name:value collection with the specified parameters. My con ...