I just implemented reducers for my sorting algorithm visualizer and am trying to set the state of my array to be the outcome of a sorting algorithm. I am 99% sure my reducer is receiving the sorted array and then returning it (because I did some console.logs), and I am also quite sure that the variable itself does change.
Here is my reducer and array variable (*note that values will be array in the function):
export const ACTIONS = {
SET_VALUES: 'set-values'
}
function reducer(state, action) {
switch (action.type) {
case ACTIONS.SET_VALUES:
console.log(action.payload.values)
return action.payload.values
default:
return state
}
}
const [values, dispatch] = useReducer(reducer, [])
And here is the sorting algorithm where dispatch is called:
export function bubbleSort(array, dispatch) {
var testArray = array
console.log('sorting')
var sorted = false
while (!sorted) {
var changed = false;
for (var i = 0; i < testArray.length-1; i++) {
if (testArray[i] > testArray[i+1]) {
changed = true;
var smaller = testArray[i]
testArray[i] = testArray[i+1]
testArray[i+1] = smaller
}
}
if (!changed) {
sorted = true
}
}
dispatch({ type: ACTIONS.SET_VALUES, payload: { values: testArray}})
console.log('sorted')
console.log(array)
}
When printing the original array (values) passed to the function, it is sorted. However, the bars on the screen which reflect the array itself do not change leading me to believe a re-render is not occurring and the bars are using an old state of the variable (values). Does anyone know how to fix this?