Brandt
Brandt

Reputation: 73

How can I access data in another component?

I'm sorry if my question is too ridiculous, because I'm new to programming.

I created a project with React, I have 3 different components: navbar, sidebar and data.

I received json data from an api using hooks in my data component.

import { useEffect, useState } from "react";

export const Data = () => {
  const [data, setData] = useState();
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);
};

Now, how can I access the "data" state in the data component from other components?

I don't want to use Context api, because I've heard that it is only used in cases where the state affects all components, like authentication

thanks in advance for your help

Upvotes: 2

Views: 472

Answers (3)

Wayne Celestin
Wayne Celestin

Reputation: 159

You could maybe use the module.exports function in the data component and then just call it in the necessary components. For example:

import { useEffect, useState } from "react";

export const Data = () => {
  const [data, setData] = useState();
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);
};

module.exports = data;

Then in the navbar component for example you call it and use it where it is necessary:

const Navbar = () => {
const data = require(../Data)
...
...
...
}

Hope it helps.

Upvotes: 0

Brandt
Brandt

Reputation: 73

Thank you to everyone who helped me. Actually, I realized that the title is not correct. What I wanted to do was to use the data brought outside the component inside the component. I did this by creating custom hooks. If anyone is curious, I leave the code below.

import { useEffect, useState } from "react";

export default function useData(id = 1) {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  return { data };
}

Then I import and use the useData hook I created in any component. (I'm not even sure it's called a hook.) Example: const {data} = useData(4)

Upvotes: 0

Devendra Kushwaha
Devendra Kushwaha

Reputation: 211

I have added few lines in your codesandbox. I think this is same that you want to achieve

codesandbox

Upvotes: 1

Related Questions