I'm trying to learn react by coding, here i have come up with this code which works ! but only i need to know how to use if else or maybe ternary operator here. What i want to achieve is this: when user comes to the page this is already there :
{sisalto.map(({ avain, value }, index) => (
<div>
<div>
<IndexBox y={avain} />
</div>
<div>
<ValueBox value={value} />
</div>
</div>
))}
and when user writes something on input then this comes instead of the first one:
{searchResults.map(({ avain, value }, index) => (
<div>
<div>
<IndexBox y={avain} />
</div>
<div>
<ValueBox value={value} />
</div>
</div>
))}
my code :
function App() {
const [data, setData] = useState([])
const [searchResults, setSearchResults] = useState([])
const [searchTerm, setSearchTerm] = useState('')
const [sisalto, setSisalto] = useState([])
const fetchData = () => {
let corsAnywhere = 'https://cors-anywhere.herokuapp.com/'
let something = 'http://ksngfr.com/something.txt'
fetch(corsAnywhere + something)
.then(response => response.text())
.then(result => {
const theDataArr = result.replace(/\n/g, ' ')
const f = theDataArr.split(' ')
setData(f)
})
}
useEffect(() => {
fetchData()
}, [searchTerm])
useEffect(() => {
const mappedResult = data.map(d => {
var propertyK = d.split(':')[0]
var propertyv = d.split(':')[1]
return {
avain: propertyK,
value: propertyv
}
})
setSisalto(mappedResult)
const results = mappedResult.filter(each => each.avain === searchTerm)
setSearchResults(results)
}, [data, searchTerm])
console.log(sisalto)
return (
<div>
<header>
<div>
<h1>something</h1>
<input
type="text"
value={searchTerm}
placeholder="Search..."
onChange={e => setSearchTerm(e.target.value)}
/>
</div>
</header>
<div>
{searchResults.map(({ avain, value }, index) => (
<div>
<div>
<IndexBox y={avain} />
</div>
<div>
<ValueBox value={value} />
</div>
</div>
))}
</div>
</div>
)
}
export default App
data i'm fetching :
/* ------------------------
2005-07-09 03:05
1:74539
2:29734
3:95426
4:35489
------------------------ */