Simple guide to decoding JSON in React Native

Currently, I am working on a react native project where I am calling an API to extract data. The extraction process is successful, but now I am facing an issue with taking arguments from the extracted data.


Axios({
  url: '/Authentification',
  method: 'get',
  baseURL: 'http://smart.netrostercloud.com/api',
  transformRequest: [
    function (data, headers) {
      return data;
    },
  ],
  transformResponse: [
    function (data) {
      // console.log(data);
      setData3(data);
    },
  ],
  headers: {
    Authorization: 'Basic UxvwJc1GWjkOCyZoIHGuCD05gDUB72sqrgK30FgILho=',
  },
});

console.log(data3);

I have utilized data3 to extract the data in my main function so that it can be viewed. Here is the link to the data: https://i.sstatic.net/7Eq0Q.png

My goal is to extract CompanyCode, UserName, Password, FirstName, and LastName from the data.

Answer №1

One thing to note is that axios is an asynchronous function, meaning it returns a promise. Personally, I prefer not to use this pattern for simple API calls. However, it can be a good approach if you are familiar with the concept and use object-oriented programming to create instances of axios for reusability and to cancel connections when a component is unmounted.

Instead, I prefer to use the following method:
const getUserData = async () => {
  try {
    const { data } = await axios.get(baseUrl + route, headers, options);
    data && setData({ username: data.user.username, ... });
    doSomething();
  } catch (error) {
    doSomething();
  }
}

Answer №2

Prior to storing any information in data3, it is important to convert the data into a string using the following method: setData3(JSON.stringify(data));

After converting the data, you can proceed with the following steps:

if (data3) {
  const COMPANY_NAME = data?.user?.CompanyCode;
  const USERNAME = data?.user?.UserName;
  const FIRSTNAME = data?.user?.FirstName;
  const LASTNAME = data?.user?.LastName;
}

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

How to modify a variable within the "beforeSend: function()" using Ajax and jQuery

I am facing an issue with my ajax contact form. The beforeSend function is supposed to validate the inputs and pass the parameters to a PHP file for sending emails. However, I always receive false instead of true even when the inputs are valid. I suspect ...

aviary usage resulted in a file_get_contents error

I successfully integrated aviary into my webpage and it's functioning properly. However, I'm encountering an issue with using the file_get_contents command to retrieve the saved image. Here's the aviary code: JS: <!-- Load Feather code ...

Receiving Output from an AJAX Request

My PHP script is set up to verify the validity of an email address, returning either true or false. I've been attempting to use AJAX to call this PHP file and pass the result back to a Javascript function, but unfortunately, I haven't been succes ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

Display handpicked ionic list view

I have put together a demonstration using this (demo) to showcase the issue I am facing. Within this demo, there is a page with a list, a button located in the header that checks the attribute of an <ion-checkbox>, and a checkbox next to the list v ...

Storing data values from a specific object key into an array in Vue: Step-by-step guide

Just dipping my toes into the world of Vue framework here. I managed to create a selectable table that stores data in an object. I want this function to run in the background, so I figured it should be in the computed section. The object structure is as fo ...

Obtaining numerical values from a string with the help of Selenium IDE

I've gone through numerous solutions for this issue and attempted all of them, but none seem to be effective. Despite its seemingly simple nature, I am struggling with the following task; My objective is to extract a numerical value from a string and ...

Risks associated with the use of Base64 encoded URLs in relation to security

When accessing my API from a web application, I'm using ajax to send get and post requests. Since I'm new to this, I'm curious about the security implications related to the content type being used. Currently, I know of two content types t ...

What sets apart jQuery's `click`, `bind`, `live`, `delegate`, `trigger`, and `on` functions, and how can they be utilized differently in coding

I have gone through the documentation for each function provided on the official jQuery website, but I couldn't find any comparison listings for the following functions: $().click(fn) $().bind('click',fn) $().live('click',fn) $().d ...

Having trouble accessing the Ajax "data" parameter in Twisted

An ajax request is made using the "POST" method with these parameters: function sendDataToServer(portNumber){ console.log(portNumber) $.ajax({url: "action", dataType : 'html', type: "POST", data: portN ...

Difficulty in accessing 2D array data from JSON in Android utilizing AsyncTask

Here is the JSON file output: { "result": [ { "Owner_ID": "1", "Owner_Name": "King", "Owner_IC": "997788-01-9267", "Owner_Contact": "012-34567890", "Owner_AccNum" : "124914848238902", "Car": { ...

What is the proper way to include onMouseOver and onMouseEnter events in a reactjs project

Seeking assistance with implementing the onMouseOver event in React, but encountering issues. I have followed the correct procedures for using, calling, and setting State. Please review my code and provide guidance. import React from 'react'; c ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

Using Function Call to Generate Components in React

Being tired of repeatedly defining states to render Components based on conditions, I often find myself just wanting to display notifications or alerts. My current dilemma is figuring out how to render a component by invoking a function from within that co ...

"Error occurs when passing data back to main thread from a web worker: undefined data received

Hello, I’ve been experimenting with using a web worker to retrieve data and send it back to the main thread. However, I've encountered an issue with my code not working as expected. onmessage = (e) => { console.log(e); if( e.data[0] === &apos ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...

Identify when JavaScript makes calls to C# methods

My team and I are currently working on a .NET MVC project in Visual Studio, where we frequently need to invoke controller or model functions from JavaScript files. An example of this is: $.ajax({ "dataType": 'json', ...

Navigating between pages using React and Material UI

My concept involves a <LandingPage> with a <Top> element that can be modified by user interaction. The <Top> component contains a pageState, which can be changed by clicking buttons on the First and Second pages. Is this considered good ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

Error encountered in jQuery's addClass and removeClass functions: Unable to read the property 'length' of an undefined value

Upon loading my page, I aim to have some of the div elements hidden initially and display only one. Here is a script that accomplishes this goal: <script> $(document).ready(function () { $(".total").click(function () { $("#pi ...