Basically I'm using two components to get data from the DB. One that I'm using to loop through them and a second one to access and view the data for each entry. I have a field in DB called 'sex' in which the users submits either male, female and/or other. I'm trying to do an if statement but it is not working or maybe I'm not that good as I though.
I have done this in the file(Secrets.js) in which I'm looping through(I'm using a different component within as well) them:
import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import SecretItem from './SecretItem';
import { getSecrets } from '../../actions/secret';
const Secrets = ({ getSecrets, secret: { secrets, loading } }) => {
useEffect(() => {
getSecrets();
}, [getSecrets]);
return loading ? (
<Spinner />
) : (
<Fragment>
<div className="container">
<Fragment>
{secrets.map(secret => (
<SecretItem key={secret._id} secret={secret} />
))}
</Fragment>
</div>
</Fragment>
);
};
Secrets.propTypes = {
getSecrets: PropTypes.func.isRequired,
secret: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
secret: state.secret
});
export default connect(
mapStateToProps,
{ getSecrets }
)(Secrets);
The problem it is not that I'm not able to fetch data because I actually can, I can get the title, date, text, etc. What the real problem is - is when wanting to fetch conditional data as said in the first paragraph. Here it is my SecretItem component:
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { deleteSecret } from '../../actions/secret';
const SecretItem = ({ secret: { _id, age, sex, text, date } }) => {
if (sex === 'male') {
const sexo = 'male';
} else if (sex === 'female') {
const sexo = 'female';
} else {
const sexo = 'other';
}
return (
<article className={`card text-center ${_id}`}>
<div className="card-header">
<span className="badge age badge-info">{age}</span>
<span className="badge sex badge-secondary">{sexo}</span>
<p>{text}</p>
<P>{date}</P>
</div>
</article>
);
};
SecretItem.propTypes = {
secret: PropTypes.object.isRequired,
deleteSecret: PropTypes.func.isRequired
};
export default connect(
null,
{ deleteSecret }
)(SecretItem);
So far it just keeps throwing me error of undefined or it simply do not display anything. Allow me to say this is my first time using React, I actually never had troubles with JavaScript so if any of you guys can guide and me and tell me what my error is, please do so.
sexois not in scope because you're assigning to it inside a block in all cases.