The Material-ui Switch is not updating when the firebase value is updated.
I posted just a part of the code here, the full Demo is available on CodeSandbox.
The project is connected to firebase and using depenedncies as: react-redux-firebase, redux-firestore, etc, you can find all details in the Demo.
import React, { Component } from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";
import Switch from "@material-ui/core/Switch";
import { toggleStatus } from "../actions/statusActions";
const Wrapper = styled.div`
padding-top: 50px;
`;
const OnOff = styled.span`
${props => `color: ${props.color}`};
`;
class Header extends Component {
hanldeToggleStats = () => {
const { status } = this.props;
const dbStatus = status && status[0].status;
this.props.toggleStatus(dbStatus);
};
render() {
const { status } = this.props;
const dbStatus = status && status[0].status;
console.log("dbStatus:", dbStatus);
return (
<Wrapper>
<div>
Change status, refresh the page, observe difference between labels and
Switch
</div>
<OnOff color={dbStatus ? "#BDBDBD" : "#7AC943"}>Off</OnOff>
<Switch
checked={dbStatus}
onChange={this.hanldeToggleStats}
color="primary"
/>
<OnOff color={dbStatus ? "#7AC943" : "#BDBDBD"}>On</OnOff>
</Wrapper>
);
}
}
const mapStateToProps = state => {
return {
status: state.firestore.ordered.status //this returns true
};
};
const mapDispatchToProps = dispatch => {
return {
toggleStatus: status => dispatch(toggleStatus(status))
};
};
export default compose(
connect(
mapStateToProps,
mapDispatchToProps
),
firestoreConnect([
{ collection: "status", limit: 1, orderBy: ["createdAt", "desc"] }
])
)(Header);
const dbStatus = Boolean(status && status[0].status);
const dbStatus = status && status[0].status;
can result indbStatus
being undefined upon which the component is considered uncontrolled. Once it gets defined you should get a warning.