RangeSlider ReactJS after post data retrieves always the iniatilize value

Viewed 41

I'm having a bug that should be my fault. I have a component responsible for controlling the brightness of a light bulb.

import React, { useState } from 'react';
import RangeSlider from 'react-bootstrap-range-slider';

const Brightness = (props) => {
    const [brightness, setBrightness] = useState(127);

    async function postBrightness (e)  {
      setBrightness(e.target.value);
      try {
              let result =  await fetch(`..../${props.id}/set`, {
                method: "POST",
                //mode: 'no-cors',
                headers: {
                  Accept: "application/json",
                  "Content-Type": "application/json"
                },
                body: JSON.stringify({
                  brightness: e.target.value
                })
              });
              console.log(result);
            } catch (e) {
              console.log(e);
            }
    }

    return (
      <div>
        Brightness:
        <RangeSlider
          value={brightness}
          step={63.5}
          min={0}
          max={254}
          onChange={async (e)=> {await postBrightness(e)}}
        />
      </div>
    );
};

export default Brightness;

As soon as I move the range slider it sends the right value, but as soon as I stop moving the range slider it returns to the initial value (127).

import React, { Component } from 'react';
import { Ring } from 'react-awesome-spinners'

import State from './State.js';
import Brightness from './Brightness';
// import ColorTemperature from './ColorTemperature';

export default class Measurement extends Component {
    constructor(props){
        super(props);
        this.state = {
            data: []
        }
    }

    data_update(){
        fetch('http://...../'+ this.props.id + '/recent_data')
            .then(response => response.json())
            .then(data => this.setState({ data: data.data }));
    }

    componentDidMount(){
        setInterval(() => this.data_update(), 2000);
    }

    
    render() {
        const { data } = this.state;

        if( !data.length ){
            return(<Ring />)
        }
        else {
            return (
                <ul>
                    {data.map(i=> (
                    <li className="measurements" key={i._id}>
                        {i.state ? (<State id={this.props.id}/>) : false}
                        {i.battery ? (<p>Battery: {i.battery}%</p>): false}
                        {i.voltage ? (<p>Voltage: {i.voltage}mV</p>) : false}
                        {i.temperature ? (<p>Temperature: {i.temperature}ºC</p>) : false}
                        {i.humidity ? (<p>Humidity: {i.humidity}%</p>) : false}
                        {i.pressure ? (<p>Pressure: {i.pressure}mBar</p>) : false}
                        {i.current>-1  ? (<p>Current: {i.current}A</p>) : false}
                        {i.consumption ? (<p>Consumption: {i.consumption}W</p>) : false}
                        {i.brightness>-1 ? (<Brightness id={this.props.id}/>) : false}
                        {/* {i.color_temp  ? (<ColorTemperature id={this.props.id}/>) : false} */}
                        {i.date ? (<p>Date: {i.date}</p>) : false}
                    </li>
                    
                    )
                 )}
                </ul>
                
        )
        }
    }
}

If someone could help me, I'd be extremely grateful. Thank you.

1 Answers

I just tested the code of your slider and it worked fine for me.

However, there is one reason why the state could reset: The component is unmounted and then mounted again. You can test this by adding

useEffect(() => {
    console.log("mounted");
    return () => console.log("unmounted");
}, []);

to your Brightness component. If you see that the component is unmounted and mounted again, then there is something wrong in the parent component. I didn't see anything obviously wrong there, but you update the data every two seconds and then you map the data:

{data.map(i=> (
    <li className="measurements" key={i._id}>

Is the key correct? Is it the same every time for the same elements? If not, this would be a reason for the unwanted mounting behavior.

Related