Home > other >  How to use variable from script A in srcript B typescript?
How to use variable from script A in srcript B typescript?

Time:05-16

I want to get variable from other script to build the next part of the page on the basis of this data.

This is code to get data from API:

import Axios from "axios";
import React from "react";

export default class PersonList extends React.Component {
  state = {
    dataURL: [],    //from this variable I want get data
  };

  componentDidMount() {
    Axios.get(
      "https://g.tenor.com/v1/search?q="  
        "mems"  
        "&key="  
        "MY_TENOR_API_KEY"  
        "&limit="  
        "1"
    ).then((res) => {
      this.state.dataURL = res.data;
      this.setState({ dataURL });
      console.log(this.state.dataURL);
    });
  }

  render() {
    return;
  }
}

Here I want to dynamically import the script and try to get access to variable from other script

import { useState } from "react";
import styles from "../styles/Form.module.scss";

function Form() {
  const [results, setResults] = useState();

  return (
    <div className={styles.container}>
      <div className={styles.form}>
        <input
          type="button"
          onClick={async (e) => {
            const { value } = e.currentTarget;

            const Fuse = (await import("../pages/api/tenor")).default;
            const fuse = new Fuse(state);    //I got there an error: "Cannot find name 'state'.ts(2304)"

            setResults(fuse.search(value));
          }}
        />
      </div>
    </div>
  );
}

export default Form;

CodePudding user response:

You can try React Redux or useReducer to share variable between components.

CodePudding user response:

Basically, if you want to access a component's data from a different component you have a few options you can choose from.

  1. Send that data as a prop.
    (only relevant if the 2nd component is a child/grand-child/etc.. of the 1st component)

  2. Manage a "global state" (a single source containing the app's relevant data).
    This can be achieved via 3rd-party libraries (Redux / MobX / etc..)
    Or even via React's built-in ContextAPI.

  3. Use a shared hook containing the state which can then be accessed from other components.
    (only relevant for functional components)

IMO, the simplest option is the 3rd, but it will require turning PersonList into a functional hook.

An example should look like this:

// Shared "PersonList" hook.

import Axios from "axios";
import React, { useState } from "react";

export function usePersonList() {
  const [dataURL, setDataURL] = useState([]);

  useEffect(() => {
    Axios.get(
      "https://g.tenor.com/v1/search?q="  
        "mems"  
        "&key="  
        "MY_TENOR_API_KEY"  
        "&limit="  
        "1"
    ).then(res => setDataURL(res.data));
  }, []);

  return dataURL;
}

// Form.tsx

import { useState } from "react";
import styles from "../styles/Form.module.scss";

function Form() {
  const [results, setResults] = useState();
  const dataURL = usePersonList();

  return (
    <div className={styles.container}>
      <div className={styles.form}>
        <input
          type="button"
          onClick={async (e) => {
            const { value } = e.currentTarget;

            const Fuse = (await import("../pages/api/tenor")).default;
            const fuse = new Fuse(dataURL);

            setResults(fuse.search(value));
          }}
        />
      </div>
    </div>
  );
}

export default Form;
  • Related