简体   繁体   中英

How to use properties of an object from a js file in another js file in the same project?

I am wondering if it is possible to use the properties of an object from a js file in another js file. In my ItemForm.js, I am sending my data to an api and I get a response. This response is a json.

const requestData = group => {
fetch("http://localhost:4996/getTagsFromWebsite", {
  method: "POST",
  headers: {
    "Content-Type": "application/json;charset=utf-8",
    "Access-Control-Allow-Origin": "*",
  },
  body: JSON.stringify(group),
})
  .then(response => {
    return response.json();
  })
  .then(data => {
    console.log(data);
  });

};

In the same project in SpecForm.js, I have to use these props to write some conditions. How can I do that? group has a series of properties and I need to use them. Here is the SpecForm.js

    import React from "react";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";

import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
import { Formik, Form, Field } from "formik";

const useStyles = makeStyles(theme => ({
  container: {
    display: "flex",
    flexWrap: "wrap",
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 400,
  },
  dense: {
    marginTop: 19,
  },
  menu: {
    width: 200,
  },
  button: {
    marginTop: theme.spacing(3),
    marginLeft: theme.spacing(1),
  },
}));

export default function SpecForm(props) {
  const classes = useStyles();

  const [values, setValues] = React.useState({
    multiline: "Controlled",
    value: "Select Item",
  });

  return (
    <React.Fragment>
      <Typography variant="h6" gutterBottom></Typography>
      <Grid container spacing={3}>
        <Grid item xs={12} sm={6}></Grid>
        <Formik
          render={({
            handleSubmit,
            handleChange,
            values,
            errors,
            touched,
            setFieldTouched,
            validateForm,
            setTouched,
            setErrors,
          }) => (
            <div>
              <Typography variant="h3" component="h2">
                The matching score is:
              </Typography>
              <Button
                variant="contained"
                color="primary"
                onClick={() => {
                  props.onNext();
                }}
                className={classes.button}
              >
                Next
              </Button>
            </div>
          )}
        />
      </Grid>
    </React.Fragment>
  );
}

Props of group have to be used in in a ternary or if condition. Thanks !

This is possibly two different questions. To use "an object from a js file in another js file". That is an import.

//cat.js
const cat = 'Nyanko'
module.exports = cat

//app.js
const cat = require('./cat')
console.log(cat) // logs Nyanko

To use async data in a different file is the same thing except you need to wait for the data to "arrive".

//userInfo.js 'https://jsonplaceholder.typicode.com/posts/1' returns a json object
const userInfo = (async function(){
  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
  const data = await response.json()
  return data
})()
module.exports = userInfo

//app.js
const userInfo = require('./userInfo')
const logId = async function(){
  const user = await userInfo
  console.log(user.userId)
}()

Same thing without async await:

//userInfo.js
const userInfo = (function(){
  const promiseData = new Promise(function(res,rej){
    fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => res(data))
    .catch(e => rej(e))
  })
  return promiseData
})()
module.exports = userInfo

//app.js
const userInfo = require('./userInfo')
.then(user => console.log(user.userId))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM