Home > front end >  I got an Error "Cannot read properties of undefined (reading 'value')" in React.
I got an Error "Cannot read properties of undefined (reading 'value')" in React.

Time:01-06

I am using React.js to create the front-end side of a web application that can control home appliances.

What I want to achieve is I have a slider (LightSliderBar.js) that can change the brightness of the light. I want to send the integer value to the backend when the slider is moved

Issue/error message

Cannot read properties of undefined (reading 'value')

The strange thing is that when I move the slider

I can see console.log(e); in handleSliderChange at console.

I am wondering why such an error occurs...

enter image description here

LightDetailOffice.js

import React, { useState, useEffect, useCallback, onClick, useLayoutEffect } from 'react';
import axios from 'axios';
import Cookies from 'universal-cookie';
import { useSelector } from "react-redux";
import { useParams, Link, useHistory } from 'react-router-dom'

import LightSliderBar from '../../slider_bar/LightSliderBar';


const LightDetail = () => {
  const history = useHistory();

  const [light, setLight] = useState([]);

  const {id} = useParams();
  const isLoggedIn= useSelector(state => state.user.isLoggedIn);

  const { entity_id } = useParams();

const getDevices = async(data) => {
  await axios.get('xxx.com',
    {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${cookies.get('accesstoken')}`
      },
    })
    .then(result => {
      console.log(result.data)
      setLight(result.data.attributes.light);  
    })
    .catch(err => {
      console.log(err);
    });
}


useEffect(() => {
  getDevices();
    }, []);


  
return (
    <div>
      <HeaderForDetailPage />
      <p className="office_top">Office</p>
      <div className="container container_light_detail">
        {isLoggedIn ? 
        <div className="row mx-auto text-center">
            <>
                  <div>
                    <LightSliderBar />
                  </div>
            </>
        </div>
        :
        <div>
            <p> You should login</p>
        </div>
        }
      </div>
    </div>
  );
}
export default LightDetailOffice;

LightSliderBarOffice.js

import React, { useState, useEffect, useCallback, onClick, useLayoutEffect } from 'react';
import axios from 'axios';
import { useParams, Link, useHistory } from 'react-router-dom'
import Cookies from 'universal-cookie';

  const LightSliderBar = () => {
    const cookies = new Cookies();
    const { entity_id } = useParams();
    const [light, setLight] = useState([]);

    const [brightness_value, setBrightnessValue] = useState();

    let percent = (brightness_value * 100) / 100;
    let gradient =`linear-gradient(to right,#3C91E6 `   percent   `%,#fff `   percent   `%)`;


  
    const handleSliderChange = (e) => {
      console.log(e);
      lightOn(e.target.value);
    }

    

    const lightOn = async(data) => {
      console.log("Body sent to server", {
      entity_id: entity_id, 
      rgb_color: [255, 255, 255],
      brightness: brightness_value
    })
      await axios.post('xxx.com',
        {
          entity_id: entity_id, 
          rgb_color: [255, 255, 255],
          brightness: brightness_value
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cookies.get('accesstoken')}`
          },
        })
        .then(result => {
          console.log('Turn on!');
          getDevices();
        })
        .catch(err => {
          console.log('Turn on Missed!');
        });
    }

    const getDevices = async(data) => {
      await axios.get('xxx.com',
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cookies.get('accesstoken')}`
          },
        })
        .then(result => {
          console.log(result.data)
          setLight(result.data.attributes.light); 
          setBrightnessValue(result.data.attributes.light.filter(c => c.entity_id === entity_id).map((item,i) =>  item.brightness)[0]);  
        })
        .catch(err => {
          console.log(err);
        });
    }
    
    useEffect(() => {
      getDevices();
    }, []);


    return (
      <div>
        <div className="range-container col-8">
          <input className="range-input" type="range" name="speed" min="0" max="100" id="slider"
          value={brightness_value} onChange={(e) => handleSliderChange(e.target.value)} style={{ background: gradient, }}></input>
          
        </div>

      </div>
    );
  };
  
  export default LightSliderBarOffice;

CodePudding user response:

You are passing the value e.target.value and you are expecting the object.

You have tojJust pass the event object.

Like this:

 onChange={(e) => handleSliderChange(e)}  

in LightSliderBarOffice.js input field.

  • Related