Pablo
Pablo

Reputation: 1

How to use a variable outside the function in React

I need to display the printCenterCode in a MenuItem. I have a function that reads a json and creates an array with the information.

In order to display the MenuItem I need to get that information out of the function. (it's in the rows[idx].label field)

This is my code

const HeaderBar = () => {

    //Calculo hora y fecha actual
    const hoy = new Date();
    const fecha = hoy.getDate() + '-' + ( hoy.getMonth() + 1 ) + '-' + hoy.getFullYear();
    const hora = hoy.getHours() + ':' + hoy.getMinutes() + ':' + hoy.getSeconds();

    const cioptions = [
        
      ];


    

    const state = useSelector( state => state);
    console.log('From HeaderBar ...');
    console.log(state);

    let rows = JSON.parse('[]') 
    let idx = 0; // add here     
     
    if(state.ui.type === types.get_ci){
        const srcRows = state.ui.payload.json;
        console.log('JSON ...');
        console.log(srcRows);
        // let idx = 0; // remove from here
        
  
        srcRows.map((item) => {
                rows.push(
                    {value: `${idx}`, label: `${item.printCenterCode}`}
                );
                console.log(rows[idx].label);
                idx++
            } 
        )  
    }


    return (
        <div>
            <Grid container xs={12} pb={4}>
                <Grid item xs={2}>
                <Box id="hlogo" pt={4} pl={4}>
                    <img 
                        src={logo} 
                        alt="logo" 
                        width={140} 
                        height={140} 
                    />
                </Box>
                </Grid>

                <Grid container xs={10}>

                    <Grid item xs={9}>
                        <Box id="title" pt={4}>
                            <Typography variant="p" className='titulo'>
                                Consola de Impresión
                            </Typography>
                        </Box>
                    </Grid>
                    <Grid item xs={3}>
                        <Box pt={4} className='fecha' >
                            <Typography variant="p">
                                {fecha} | {hora}
                            </Typography>
                        </Box>
                    </Grid>
                        <Grid item xs={1} container pt={4}/>

                        <Grid item xs={4} container pt={4}>
                            
                                    <label 
                                        htmlFor="ci"
                                        className='ci'
                                    >                   
                                        Documentos del centro de impresión  :         
                                    </label>
                                
                                
                                    <div style={{ display: 'flex', alignItems: 'flex-end', columnGap: 8, paddingLeft: 9, paddingBottom: 6  }} >
                                        <TextField 
                                            size="small"
                                            label=""
                                            sx={{ width: 100 }}
                                            select
                                            style={{borderRadius: 0}}
                                        >
                                            
                                            { rows[idx] && rows[idx].label ? 
                                                <MenuItem key={rows[idx].label}>
                                                {rows[idx].label}
                                                </MenuItem> : null
                                            }
                                            )
                                        </TextField>
                                    </div>

                        </Grid>

                        <Grid item xs={3} container pt={4}>
                            
                            <label 
                                htmlFor="nombre"
                                className='user'
                            >                   
                                Usuario:         
                            </label>
                                    
                            <div style={{ display: 'flex', alignItems: 'flex-end', columnGap: 8, paddingLeft: 9, paddingBottom: 6  }} >
                                
                                    <TextField 
                                        id="outlined-basic" 
                                        size="small"
                                        label=""
                                        sx={{ width: 200 }}  
                                    />                               
                                
                            </div>

                        </Grid>
                        <Grid item xs={2} container pt={4} ml={-7}>
                            <IconButton color="primary" sx={{ p: '10px' }} aria-label="directions">
                                <ReplayIcon />
                            </IconButton>
                        </Grid>
                </Grid>
            </Grid>
        </div>
    )
  }
  
  export default HeaderBar

in this way, the error that I get is that idx is not defined

Upvotes: 0

Views: 161

Answers (1)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

For workaround you can do is

let rows = JSON.parse('[]') 
let idx = 0; // add here     
     
 let rows = JSON.parse('[]') 
    if(state.ui.type === types.get_ci){
        const srcRows = state.ui.payload.json;
        console.log('JSON ...');
        console.log(srcRows);
        // let idx = 0; // remove from here
        
  
        srcRows.map((item) => {
                rows.push(
                    {value: `${idx}`, label: `${item.printCenterCode}`}
                );
                console.log(rows[idx].label);
                idx++
            } 
        )  
    }

...
...

{ rows[idx] && rows[idx].label ? 
  <MenuItem key={rows[idx].label}>
      {rows[idx].label}
  </MenuItem> : null
}
...

Upvotes: 1

Related Questions