Skip to content

React connecting info between App.js and a class

I am trying to integrate React Scheduler into my app that uses JSON data base. how can I pass the shifts and functions defined in App.js that update the data to DataSheet.js and use them instead of the defaults? Is there a better way to enable the database update from the DataSheet?

App.js:

import React from 'react';
import Header from "./components/Header";
import { useState, useEffect } from "react"
import AddShift from './components/AddShift';
import Shifts from './components/Shifts';
import Week from './components/Week'
import DataSheet from './components/DataSheet';

const containerStyle= {
  width: '100vw',
  height: '100vh',
}

const App = () => {
  const [showAddShfit, setShowAddShift] = useState(false)
  const [shifts, setShifts] = useState([])

  useEffect(() => {
    const getShifts = async () => {
      const shiftsFromServer = await fetchShifts()
      setShifts(shiftsFromServer)
    }
    getShifts()
  }, [])

  const fetchShifts = async () => {
    const res = await fetch(`http://localhost:5000/shifts/`)
    const data = await res.json()
    return data
  }

//Add Shift
const addShift = async (shift) => {
  const res = await fetch(`http://localhost:5000/shifts/`,{
    method: 'POST',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify(shift)
  })

  const data = await res.json()

  setShifts([...shifts, data])
}

const deleteShift = async (id) => {
  await fetch(`http://localhost:5000/shifts/${id}`, {
    method: 'DELETE',
  })

  setShifts(shifts.filter((shift) => shift.id !== id))
}  

  return (
    <div className="container"
    style={containerStyle} >
      <div className='secondary_container'>
        <Header />
        <DataSheet shifts={shifts} addShift={addShift}/>
      </div>
    </div>
  );
}
export default App;

DataSheet.js:

import * as React from 'react';
import Paper from '@material-ui/core/Paper';
import { ViewState, EditingState } from '@devexpress/dx-react-scheduler';
import {
  Scheduler,
  Appointments,
  AppointmentForm,
  AppointmentTooltip,
  WeekView,
  ConfirmationDialog,
} from '@devexpress/dx-react-scheduler-material-ui';

const appointments = [
    {
      title: "Website Re-Design Plan",
      startDate: new Date(2018, 5, 25, 9, 35),
      endDate: new Date(2018, 5, 25, 11, 30),
      id: 0,
      location: "Room 1"
    },
  ];
  
export default class DataSheet extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: appointments,
      currentDate: '2018-06-27',
      addedAppointment: {},
      appointmentChanges: {},
      editingAppointment: undefined,
    };

    this.commitChanges = this.commitChanges.bind(this);
    this.changeAddedAppointment = this.changeAddedAppointment.bind(this);
    this.changeAppointmentChanges = this.changeAppointmentChanges.bind(this);
    this.changeEditingAppointment = this.changeEditingAppointment.bind(this);
  }

  changeAddedAppointment(addedAppointment) {
    this.setState({ addedAppointment });
  }

  changeAppointmentChanges(appointmentChanges) {
    this.setState({ appointmentChanges });
  }

  changeEditingAppointment(editingAppointment) {
    this.setState({ editingAppointment });
  }

  commitChanges({ added, changed, deleted }) {
    this.setState((state) => {
      let { data } = state;
      if (added) {
        const startingAddedId = data.length > 0 ? data[data.length - 1].id + 1 : 0;
        data = [...data, { id: startingAddedId, ...added }];
      }
      if (changed) {
        data = data.map(appointment => (
          changed[appointment.id] ? { ...appointment, ...changed[appointment.id] } : appointment));
      }
      if (deleted !== undefined) {
        data = data.filter(appointment => appointment.id !== deleted);
      }
      return { data };
    });
  }

  render() {
    const {
      currentDate, data, addedAppointment, appointmentChanges, editingAppointment,
    } = this.state;

    return (
      <Paper>
        <Scheduler
          data={data}
          height={660}
        >
          <ViewState
            currentDate={currentDate}
          />
          <EditingState
            onCommitChanges={this.commitChanges}
            addedAppointment={addedAppointment}
            onAddedAppointmentChange={this.changeAddedAppointment}
            appointmentChanges={appointmentChanges}
            onAppointmentChangesChange={this.changeAppointmentChanges}
            editingAppointment={editingAppointment}
            onEditingAppointmentChange={this.changeEditingAppointment}
          />
          <WeekView
            startDayHour={9}
            endDayHour={17}
          />
          <ConfirmationDialog />
          <Appointments />
          <AppointmentTooltip
            showOpenButton
            showDeleteButton
          />
          <AppointmentForm />
        </Scheduler>
      </Paper>
    );
  }
}

Answer

Pass the data as props from parent component App and capture it from the child component DataSheet.

App

...

<DataSheet shifts={shifts} addShift={addShift}/>

...

Inside Datasheet component you can use them as this.props.shifts and this.props.addShift.