Skip to main content

Trigger child component to re-render in parent component

I'm using react-native to make an app. when onReserve() is implemented, I want ModalView to be updated. But it's not updated, value of usermachine in Modalview is the same as the value before onReserve() is implemented.

let first value of usermachine is [] and the value is changed to [{"id":"1"}] after onReserve(). but usermachine displayed on Modalview is still [] and let the value of usermachine is changed to [{"id":"2"}] after onReserve() is implemented once again,usermachine displayed on Modalview is [{"id":"1"}].

How to update the value of usermachine displayed on Modalview right after onReserve()?

ReserveScreen.js

import React, {useEffect, useState, useRef} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StyleSheet,
  View,
  Alert,
  Button,
  Text,
  Modal,
  KeyboardAvoidingView,
} from 'react-native';
import ModalView from '../components/ModalView.js';
import MachineView from '../components/MachineView.js';
import AsyncStorage from '@react-native-async-storage/async-storage';

const ReserveScreen = ({navigation, route, category}) => {
  const [machines, setMachines] = useState([]);
  const [change1, setChange1] = useState(0); 
  function handlechange() {
    setChange1(change1 + 1);
  }

  const [loading, setLoading] = useState(0);
  const [loading2, setLoading2] = useState(0);

  const getmachineinfo = () => {
    setLoading2(loading2 + 1);
    fetch(
      'https://so6wenvyg8.execute-api.ap-northeast-2.amazonaws.com/dev/machine',
      {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      },
    )
      .then(response => response.json())
      .then(json => {
        let machinelist = [];
        for (let k = 0; k < json.machinearr.length; k++) {
          let id1 = -1;
          let name1 = '';
          let category1 = -1;
          let waitnum1 = -1;
          for (let i = 0; i < json.machinearr[k].length - 1; i++) {
            switch (i) {
              case 0:
                id1 = Number(json.machinearr[k][i]);
                break; //machineid
              case 1:
                name1 = json.machinearr[k][i];
                break; //machinename
              case 2:
                category1 = Number(json.machinearr[k][i]);
                break; //machinecategory
              case 3:
                continue; //machineimage
              case 4:
                waitnum1 = json.machinearr[k][i].length;
                break; //waitnumber
            }
          }
          let object = {
            name: name1,
            id: id1,
            waitnum: waitnum1,
            category: category1,
          };
          machinelist.push(object);
        }
        setMachines(machinelist);
        setTimeout(() => {
          setLoading(loading+1);
        }, 1000);
      })
      .catch(error => {
        console.error(error);
        return -1;
      });
  };
  useEffect(() => {
    console.log('useeffect');
    getmachineinfo();
  }, [change1]); 

  const [username, setUsername] = useState(''); 
  

  const getusername = async () => {
    try {
      const name = await AsyncStorage.getItem('@storage_username');
      setUsername(name);
      return;
    } catch (e) {
      console.log(e);
    }
  };
  getusername();
  
  const [userid,setUserid]=useState('');
  const getuserid= async()=>{
    const value = await AsyncStorage.getItem('@storage_userid');
    if (value !== null){
        setUserid(value);
    }
  }
  getuserid();
  
  const [myres, setMyres] = useState([]);
  const [loading3, setLoading3] = useState(0);
  const [loading4, setLoading4] = useState(0);
  const [usermachine, setUserMachine] = useState([]);

  const myReserve = () => {
          if (userid !== null) {
        const url =
          'https://so6wenvyg8.execute-api.ap-northeast-2.amazonaws.com/dev/reservation?userid=' +
          userid;
        fetch(url, {
          method: 'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        })
          .then(response => response.json())
          .then(json => {
            Alert.alert(JSON.stringify(json));
            setMyres(json["reservation"]);
            setUserMachine(myres);
            setLoading4(loading4 + 1);
            handlechange();
            return myres;
          })
          .catch(error => {
            console.error(error);
          });
      }
    handlechange();
        
  };

  const [isreserved, setIsReserved] = useState(false);

  const onmyReserve = () => {
    setLoading3((loading3)=>{return loading3+1});
     myReserve();
    setTimeout(() => {
      if (myres.length > 0) {
        setIsReserved(true);
      } else {
        setIsReserved(false);
      }
         }, 2000);
  }; 

  const [visible, setVisible] = useState(false); 

  return (
    <SafeAreaView style=>
      <Modal transparent={true} visible={visible} animationType="slide">
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            {loading3!=loading4?(<View style=>
          <View style= />
          <Text>현재 예약가능한 기구가 없습니다.</Text>
          <View style= />
        </View>):(<ModalView
              isreserved={isreserved}
              usermachine={usermachine}
              handlerFunction={handlechange}
              change1={change1}></ModalView>)}
            
            <Button
              title={'확인'}
              onPress={() => {
                setVisible('false');
              }}></Button>
          </View>
        </View>
      </Modal>
      <View style={styles.btn1view}>
        <Button
          title="나의 예약내역 조회/수정"
          color={'#26a96a'}
          onPress={() => {
            onmyReserve();
            setVisible(true);
          }}
        />
      </View>
      <View style={styles.seperator}></View>
      {loading != loading2 ? (
        <View style=>
          <View style= />
          <Text>현재 예약가능한 기구가 없습니다.</Text>
          <View style= />
        </View>
      ) : (
        <MachineView
          machine={machines}
          handlerFunction={handlechange}
          change1={change1}></MachineView>
      )}
      <View style=></View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  seperator: {
    height: 1,
    backgroundColor: 'black',
    marginVertical: 10,
  },
  btn1view: {
    flex: 0.6,
    backgroundColor: 'white',
    flexDirection: 'row-reverse',
    alignItems: 'center',
  },
  categoryView: {
    flex: 0.5,
    backgroundColor: 'white',
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  sortView: {flex: 0.5, flexDirection: 'row', marginLeft: 10},
  scrollView: {flex: 6, backgroundColor: 'white'},
  modalContainer: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
  },
  modalContent: {
    flex: 0.5,
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'black',
    borderWidth: 4,
    borderRadius: 20,
  },
});

export default ReserveScreen;

ModalView.js

import React from 'react';
import {View, Text, Button, StyleSheet} from 'react-native';
import MachineModal from './MachineModal.js';
import Icon from 'react-native-vector-icons/MaterialIcons';
const ModalView = ({isreserved, usermachine, change1, handlerFunction}) => {
  const change2 = change1;
  function handleChange() {
    handlerFunction();
    console.log('handlechange()');
  }
  
  {
      return (
        <View>
          <Text>나의 예약내역</Text>
          {usermachine.map(item => {
            return (
              <View key={item.id}>
                <MachineModal
                  name={item.name}
                  id={item.id}
                  waitnum={item.waitnum}
                  change2={change2}
                  handlerFunction={handleChange}></MachineModal>
              </View>
            );
          })}
        </View>
      );
    
  }
};

const styles = StyleSheet.create({});
export default ModalView;

MachineModal.js

import React, {useState} from 'react';
import {View, Text, Button, Alert, StyleSheet, Image} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage'; 


const MachineModal = ({name, id, waitnum, change2, handlerFunction}) => {
  const formatted = `기구명 : ${name}\n\n현재 대기인원 : ${waitnum}명`;
  const [userid, setUserid] = useState('');
  const getusername = async () => {
    try {
      const uid = await AsyncStorage.getItem('@storage_userid');
      setUserid(uid);
      return;
    } catch (e) {
      console.log(e);
    }
  };
  getusername();

  const change3 = change2;
  function handlechange1() {
    handlerFunction();
  }

  const machinereturn = (machineid, usid) => {
    try {
      fetch(
        'https://so6wenvyg8.execute-api.ap-northeast-2.amazonaws.com/dev/return',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            machineid: String(machineid),
            userid: String(usid),
          }),
        },
      )
        .then(response => response.json())
        .then(json => {
          console.log(json);
          try {
            tim = json['time'];
            handlechange1();
            Alert.alert('반납되었습니다.');
            return 1;
          } catch (e) {
            handlechange1();
            Alert.alert('반납에 실패했습니다.');
            return -1;
          }
        });
    } catch (e) {
      console.log('17');
      console.log(e);
    }
  };

  return (
    <View style={styles.machine}>
      <Image
        source={require('../images/default_image.png')}
        style=></Image>
      <Text>{formatted}</Text>
      <Button
        title="예약취소"
        onPress={() => machinereturn(id, userid)}></Button>
    </View>
  );
};

const styles = StyleSheet.create({
  machine: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingTop: 7,
    paddingBottom: 7,
    borderBottomColor: 'black',
    borderBottomWidth: 1,
    alignItems: 'center',
  },
});
export default MachineModal;
Via Active questions tagged javascript - Stack Overflow https://ift.tt/NSalmI1

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data