Home > Back-end >  export or send data in react
export or send data in react

Time:12-24

How can I export my data from a react stateful component to a simple JS file??

for example: From here: (I want to export dates)

function Calendar() {
  const [selectedDay, setSelectedDay] = useState([
   {year: 2021, month:11, day:11},
   {year: 2022, month: 1, day: 2,
  ]);

  const dates = selectedDay.map(d => d)
}

To here a simple js file ( builder.js ):

(I want to show dates in ..... place)

export const buildDaysCells = () => {
  const v = [];
  for (let i = 0; i < MONTHS_PER_YEAR * NUM_OF_YEARS; i  = 1) {
    const startMonth = i;
    v.push({
      id: `m${startMonth}`,
      title: `${DAYS_NAMES[i]} ${......}`, 
    });
  }
  return v;
};

CodePudding user response:

You can set a parameters for buildDaysCells and pass it in ...

export const buildDaysCells = (dates) => {
  const v = [];
  for (let i = 0; i < MONTHS_PER_YEAR * NUM_OF_YEARS; i  = 1) {
    const startMonth = i;
    v.push({
      id: `m${startMonth}`,
      title: `${DAYS_NAMES[i]} ${dates}`, 
    });
  }
  return v;
};

then in first component you can pass dates

function Calendar() {
  const [selectedDay, setSelectedDay] = useState([
   {year: 2021, month:11, day:11},
   {year: 2022, month: 1, day: 2,
  ]);

  const dates = selectedDay.map(d => d)

  console.log(buildDaysCells(dates)) // You can check this part in your console
}

CodePudding user response:

The official answer is, "You can't", reference. You need to change these codes into hooks:

function useCalendarDates() {
    const [selectedDay, setSelectedDay] = useState([
        { year: 2021, month: 11, day: 11 },
        { year: 2022, month: 1, day: 2 },
    ]);

    const dates = selectedDay.map(d => d);

    return dates;
}

export const useBuildDaysCells = () => {
    const dates = useCalendarDates();
    const v = [];
    for (let i = 0; i < MONTHS_PER_YEAR * NUM_OF_YEARS; i  = 1) {
        const startMonth = i;
        v.push({
            id: `m${startMonth}`,
            title: `${DAYS_NAMES[i]} ${dates}`,
        });
    }
    return v;
};

CodePudding user response:

You can achieve this by getting data from function since variable will only get their data only function the function is called in react component. In data file

import react, { useState } from "react";

function getData() {
  return [
    { year: 2021, month: 11, day: 11 },
    { year: 2022, month: 1, day: 2 },
  ];
}

function Calendar() {
  const [selectedDay, setSelectedDay] = useState(getData());

  const dates = selectedDay.map((d) => d);
}

export { Calendar, getData };

In recieving file:

import React from "react";
import { getData } from "./result";

const App = () => {
  console.log(getData());
  return <div>{JSON.stringify(getData())}</div>;
};

export default App;

  • Related