Creating Dynamic UI in React Native by Displaying POST Request Data on Screen

Here's a scenario where I have set up a post route:

router.post("/projects", async (req, res) => {
  const {
    projectName,
    projectDescription,
    projectBudget,
    projectDuration,
    industry,
    companyName,
    numberOfEmployees,
    diamond,
  } = req.body;
  console.log(diamond);

  const [projectDiamond] = diamond;

  const { criteria } = projectDiamond;

  if (
    !projectName ||
    !projectDescription ||
    !projectBudget ||
    !projectDuration ||
    !industry ||
    !companyName ||
    !numberOfEmployees ||
    !diamond
  ) {
    return res.status(422).send({ error: "Must provide all project details" });
  }

  try {
    const project = new Project({
      projectName,
      projectDescription,
      projectBudget,
      projectDuration,
      industry,
      companyName,
      numberOfEmployees,
      diamond,
      userId: req.user._id,
    });

    const recommendation = await Recommendation.find({
      "diamond.criteria": criteria,
    }); 

    const projectsWithSameDiamond = await Project.find({
      "diamond.criteria": criteria,
    }); 
    
    const projectsWithSameIndustry = await Project.find({ industry }); 
    
    await project.save();
   
    
  } catch (err) {
    res.status(422).send({ error: err.message });
  }
});

Let's discuss how to utilize these data in a React Native component. Starting with a component called A.js:

const A = () => {
 return(
  //returning something here
 )
)
}

If this component uses axios to send a POST request to the defined route:

const A = () => {
 ...
 axios.post("/projects", {projectName,
    projectDescription,
    projectBudget,
    projectDuration,
    industry,
    companyName,
    numberOfEmployees,
    diamond} );
 return(
  //returning something here
 )
)
}

Once the request is successful and a project is posted, how can we display those variables on screen?

const A = () => {
 return(
  <Text>{recommendation}</Text> {/*Not sure how to get this after posting a new project */}
  <Text>{projectWithSimilarDiamond}</Text> {/*Not sure how to get this after posting a new project */}
  <Text>{projectWithSimilarIndustry}</Text> {/*Not sure how to get this after posting a new project */}
 
 )
)
}

Answer №1

Check out this example utilizing state

snack:

code:

import * as React from 'react';
import { Text, View, StyleSheet, ActivityIndicator } from 'react-native';
import Constants from 'expo-constants';
import Axios from 'axios';

// You can import various components and modules here
import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';

export default function App() {
  const [state, setState] = React.useState({
    loading: false,
    data: [],
    error: false,
  });
  
  const getPosts = async () => {
    setState({
      ...state,
      loading: true,
      data: [],
      error: false,
    });

    // try {
    //   const response = await Axios.post('/users/post', {
    //     //datas
    //   });
    //   
    //   setState({
    //     ...state,
    //     loading: false,
    //     data: response.data,
    //   });
    // } catch (err) {
    //   setState({
    //     error: true,
    //   });
    // }
  };

  React.useEffect(() => {
    getPosts()
  }, [])
  
  return (
    <View style={styles.container}>
      {state.loading ? (
        <ActivityIndicator />
      ) : (
        state.data.map(({ title }, key) => {
          <Text {...{ key }}>{title}</Text>;
        })
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

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

Maintaining TextBox State in ASP.Net Through Postbacks

Can anyone help me figure out how to maintain the control state that has been modified in Javascript? I am working with two TextBoxes, one DropDownList, and a button (all Runat=Server) in C# ASP.net 2010 Express. The first textbox accepts any user in ...

Unable to display Polygon using ReactNativeMaps

Having trouble displaying the polygon correctly on my screen. I suspect it's due to receiving an array of objects from my API. This is the code snippet in question: <MapView.Polygon coordinates={poligonofinale} strokeColor="#000" fillColor= ...

The production build of Angular 2 with special effects amplification

I am currently working on an Angular 2 Beta 8 app that I need to bundle and minify for production deployment. Despite configuring the system to generate a Single File eXecutable (SFX) bundle, I am encountering issues with creating a minified version of the ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Is there a way to convert datetime format to date in a Vue component?

With my Vue component set up like this: <template> ... <td>{{getDate(item.created_at)}}</td> ... </template> <script> export default { ... methods: { getDate(datetime) { ...

The componentDidUpdate method ensures equality between the previous and current states

Within a dashboard, the layout data for each module (utilizing react-grid-layout) is stored separately from the module data and both are saved in a database. The Dashboard component state holds the current module data and layout data. I'm attempting t ...

How can Cheerio help you effortlessly and stylishly locate tags that meet various specific criteria?

I am attempting to scrape data from the webpage . Specifically, I am looking for all the <li> tags that are nested within an <ul> tag, which in turn is located inside a div with the class mw-parser-output and has a property of title. Is there ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...

Struggling to make Datatables function properly with basic JSON data

As a newcomer to frontend development, I'm attempting to convert a JSON call into a table format. After researching, it seems like datatables is the best tool for this task. However, I'm struggling to make it work. Here is my JSON GET call: GET ...

Embracing Promises and Managing Errors in ExpressJS Middleware

When working with error handling middleware and routes that return promises in ExpressJs, it can be cumbersome to manually append .catch(err => next(err)) after every promise. Shouldn't ExpressJs automatically call the error handling middleware if ...

Issue with Vue Application: Footer is failing to render, resulting in 2 errors and a warning

Currently, I am in the process of revising and experimenting with VUE 3. I decided to create a Task Tracker application but ran into an issue when trying to add a footer. A few problems arose: It's important to note that I attempted to integrate Vue- ...

Display React elements on the web page

Seeking assistance from anyone! I've been grappling with a problem and can't seem to figure out a solution. Here's the scenario: My current setup involves a sidebar and a top bar for navigation in React. Check out my app so far in this imag ...

Verify whether the keys of Object1 exist in Object2; if they do, compare their corresponding values

How can I accomplish the following task? I want to check if the keys of object1 are present in object2. If a key is found, I need to compare its value with that of object2. If the values are different, I should replace the value in object2 with the one fro ...

The error message `fablinker.php:343 Uncaught TypeError: $(...).dialog is not a function` indicates that

When attempting to call a function on click, I'm encountering an error in the console. I've researched various solutions on Stack Overflow such as checking for jQuery duplication, but haven't had success. Any suggestions? https://i.ssta ...

Click twice for the ajax to load

Initially, I encountered an issue where nothing would load on the first hover, but it would work upon mousing off and then back on. My goal is to ensure that ajax content loads smoothly on the initial hover event. index.html <span title="" id="test" c ...

React Native is throwing an error: "Invalid hook call. Hooks must be invoked inside a function component's body."

Exploring custom hooks in my React Native app has been an interesting journey. I recently created a hook to retrieve user coordinates, but encountered a warning every time I called my useGeolocation hook within the handleUpdateLocation method: Error: Inval ...

Building a Multi-Language React Application with Real-Time Data

Is there a way for users to input data in their chosen language (English, French, German) and have that data saved in all three languages in the Database so they can view it based on their language selection? I've experimented with React-Intl and I18 ...

Determine whether an array is undefined in a React component

I am facing an issue in my React component where I have a code that renders the match name. However, sometimes the current match has an empty object and I don't know how to fix this problem. Here is the component code: import React from 'react&ap ...

press a button and choose an option from a dropdown menu on a website

Visiting a webpage within an iframe without scripting access at: This page is enclosed in another page located at: . My goal is to automatically click the "Schedule Now" button when accessing the docmein.com page. Once the "Request New Appointment" popu ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...